In adding a new array key, we’ll need to know two array functions called array_key_exists and array_merge.

First, let’s take a look at array_keys. It’s a function that returns an array containing the keys of an array.

<?php
$a = array("foo"=>"1","bar" => "2");
$keys = array_keys($a);

print_r($keys);
?>

Second, of course, is array_merge. As the name implies, it just merge the two array.

<?php
$a = array("foo" => "1", "bar" = "2");
$b = array("name" => "Juan", "gender" => "male");
$c = array_merge($b, $a);

print_r($c);
?>

So here’s the final code we have.

<?php
$a = array("foo" => "1", "bar" = "2");
// keys to be added
$b =array("name" => "Juan");
$c =array("gender" => "male");

$a = array_merge($a, $b, $c);

print_r($a);

?>

The code above is too simplistic ( we didn’t even use the array_keys function) but if you are not certain with the keys you of the array to be merged, then this functions become handy. Example as below.

<?php
$a = array("foo" => "1", "bar" = "2");
/* let's say $b comes from a function that returns
array with (i.e, array("name" => "Juan", "gender" => "male"))
*/
$b = my_function_ret_array();

$keys = array_keys($b);
foreach($keys as $key){
if(array_key_exists($key, $a){
$a[$key] = $b[$key];
}
else {
$a = array_merge($a, array($key => $b[$key]));
}
}

print_r($a);

?>

Again, I must remind my readers that there might be better way of doing this. It all depends on the situation and for the time being, this is the functions I used. If you want to suggest a new one, please share it in the comment box.

Comments are closed.

Post Navigation