Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically inserting value to array with index

Pushing values to an array caused the index to start with 0 if the index were any other values except starting from 0.

$a=array("a"=>"Dog","b"=>"Cat");
array_push($a,"Horse","Bird");

this will insert Horse and Bird with index 0 and 1.

Can I insert those values with different index? like

speed => Horse
fly => Bird
like image 471
bunkdeath Avatar asked Sep 01 '25 11:09

bunkdeath


2 Answers

Yes, by not using array_push at all:

$a['speed'] = 'Horse';
$a['fly'] = 'Bird';
like image 79
ThiefMaster Avatar answered Sep 04 '25 00:09

ThiefMaster


What's wrong with array_merge()? It's a great solution for modifying and/or appending data to large arrays.

$a = array('a' => 'Dog', 'b' => 'Cat');
$a = array_merge($a, array('speed' => 'Horse', 'fly' => 'Bird'));
var_dump($a);
// Outputs:
// array(4) {
//  ['a']=>
//      string(3) 'Dog'
//  ['b']=>
//      string(3) 'Cat'
//  ['speed']=>
//      string(5) 'Horse'
//  ['fly']=>
//      string(4) 'Bird'
// }

From The PHP Group:

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

like image 27
Daerik Avatar answered Sep 04 '25 00:09

Daerik