Skip to content

php: Add value to exsiting key in array

I have an array:

$my_array = ["name" => "John", "email" => "[email protected]"]

I want to add one or more value to the “email”. What I want to achieve is:

$my_array = ["name" => "John", "email" => "['[email protected]', '[email protected]']"]

Is there a way to push it?

Advertisement

Answer

You can do this, but you should be clear that it’s what you want to do. If you change the datatype of any part of your program there could be unexpected knock on effects (e.g. does your program check if $my_array['email'] is a string or an array)

$my_array = ["name" => "John", "email" => "[email protected]"];

// if $my_array[email] is originally defined as a string
// convert the value to an array and include the original value
$my_array['email'] = [$my_array['email'], '[email protected]'];

var_dump($my_array);
/**
array(2) {
    ["name"]=> string(4) "John"
    ["email"]=> array(2) {
      [0]=> string(19) "[email protected]"
      [1]=> string(20) "[email protected]"
  }
}
**/

// if it's always an array just push the value in
$my_array = ["name" => "John", "email" => ["[email protected]"]];
$my_array['email'][] = "[email protected]";


var_dump($my_array);
/**
array(2) { 
    ["name"]=> string(4) "John" 
    ["email"]=> array(2) { 
        [0]=> string(19) "[email protected]" 
        [1]=> string(24) "[email protected]" } }
 */
User contributions licensed under: CC BY-SA
3 People found this is helpful