How do i push a new key value pair to an array php?

31,421

Solution 1

You can add them individually like this:

$array["key"] = "value";

Collectively, like this:

$array = array(
    "key"  => "value",
    "key2" => "value2"
);

Or you could merge two or more arrays with array_merge:

$array = array( "Foo" => "Bar", "Fiz" => "Buz" );

$new = array_merge( $array, array( "Stack" => "Overflow" ) );

print_r( $new );

Which results in the news key/value pairs being added in with the old:

Array
(
  [Foo] => Bar
  [Fiz] => Buz
  [Stack] => Overflow
)

Solution 2

You can do this: $email['headers']['BCC'] = "[email protected]" but you need to add it after the if.

Share:
31,421
Tallboy
Author by

Tallboy

You’ll never be as lazy as whoever named the fireplace.

Updated on February 26, 2020

Comments

  • Tallboy
    Tallboy about 4 years

    I know there is a lot of documentation around this but this one line of code took me ages to find in a 4000 line file, and I would like to get it right the first try.

    file_put_contents($myFile,serialize(array($email_number,$email_address))) or die("can't open file");
        if ($address != "[email protected]") {
            $email['headers'] = array('CC' => '[email protected]');
        }
    }
    

    After this if statement I basically want to add on

    'BCC' => '[email protected]'

    into the $email['headers'] array (so it adds it whether the if evaluates to true or not)