Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 322
Tallboy Avatar asked May 30 '12 05:05

Tallboy


People also ask

How do you push a key in an array?

Just assign $array[$key] = $value; It is automatically a push and a declaration at the same time.

How push value from one array to another in PHP?

The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).

What is Array_keys () used for in PHP?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.

Can arrays store key value pairs?

Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well.


1 Answers

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
)
like image 181
Sampson Avatar answered Oct 26 '22 23:10

Sampson