array_push() with key value pair
To add an element to the end of an array with a key-value pair in PHP, you can use the array_push()
function.
Here's an example of how to use array_push()
to add an element with a key-value pair to an array:
<?php
$array = array('apple', 'banana');
array_push($array, 'mango', 'pear');
print_r($array);
Output:
Array ( [0] => apple [1] => banana [2] => mango [3] => pear )
Watch a video course
Learn object oriented PHP
To add an element with a key-value pair, you can pass an associative array to array_push()
, like this:
<?php
$array = array('apple' => 'red', 'banana' => 'yellow');
array_push($array, array('mango' => 'orange', 'pear' => 'green'));
print_r($array);
Output:
Array ( [apple] => red [banana] => yellow [0] => Array ( [mango] => orange [pear] => green ) )
Note that the key-value pair is added as an element with a numerical key (0 in this case). If you want to preserve the keys, you can use the $array[] =
syntax instead:
<?php
$array = array('apple' => 'red', 'banana' => 'yellow');
$array['mango'] = 'orange';
$array['pear'] = 'green';
print_r($array);
Output:
Array ( [apple] => red [banana] => yellow [mango] => orange [pear] => green )