Skip to content
Advertisement

php: Add value to exsiting key in array

I have an array:

$my_array = ["name" => "John", "email" => "example@example.com"]

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

$my_array = ["name" => "John", "email" => "['example@example.com', 'example2@example2.com']"]

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" => "example@example.com"];

// 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'], 'mynewvalue@email.com'];

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

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


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