views:

345

answers:

5

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 don't know how many items there are in the array.
  • Some items can be deleted which explains the missing [1] key.

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.

+7  A: 

The correct way to do this is:

$array[] = array(
  'width' => 200,
  'height' => 500,
);

because you're actually adding a new array to $array.

cletus
+4  A: 

How about

$array[] = array("width" => "300", "height" => "500");
Matti Virkkunen
+1  A: 

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.

Arda Xi
+2  A: 

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;
Matijs
I didn't even realise you could assign a reference in PHP. Thanks.
Arda Xi
+2  A: 

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;
zaf