Reputation: 24768
In PHP I have an array that looks like this:
$array[0]['width'] = '100';
$array[0]['height'] = '200';
$array[2]['width'] = '150';
$array[2]['height'] = '250';
I want to add a new item after this, like this:
$array[]['width'] = '300';
$array[]['height'] = '500';
However the code above don't work, because it adds a new key for each row. It should be the same for the two rows above. A clever way to solve it?
An alternative solution would be to find the last key. I failed trying the 'end' function.
Upvotes: 1
Views: 2117
Reputation: 2553
Another solution, useful when you cannot add both values in a single statement:
$a = array();
$array[] &= $a; // Append a reference to the array, instead of a copy
$a['width'] = '300';
$a['height'] = '500';
But you can also retrieve the last key in the array:
$array[]['width'] = '300';
end($array); // Make sure the internal array pointer is at the last item
$key = key($array); // Get the key of the last item
$array[$key]['height'] = 300;
Upvotes: 2
Reputation: 23244
Or, just for completeness and obviousness, use a temporary array:
$t=array();
$t['width']='300';
$t['height']='500';
And then add it to the main array:
$array[]=$t;
Upvotes: 3
Reputation: 2666
If you don't mind it losing those keys, you could easily fix the problem by re-indexing.
$array = array_values($array);
$i = count($array);
$array[$i]['width'] = '300';
$array[$i]['height'] = '500';
However, if you don't want to do this, you could also use this:
$array[] = array(
'width' => '300',
'height' => '500'
);
Which will create a new array and inserts it as a second dimension.
Upvotes: 1
Reputation: 65126
How about
$array[] = array("width" => "300", "height" => "500");
Upvotes: 5
Reputation: 625087
The correct way to do this is:
$array[] = array(
'width' => 200,
'height' => 500,
);
because you're actually adding a new array to $array
.
Upvotes: 9