php – Getting a reference to the last item of an array-ThrowExceptions

Exception or error:

I can use the following to get the value of the last item of $array. How can I get a reference to that item?

$last_item = end($array);

The items of $array are indexed arrays.

How to solve:
end($array);
$referenceToLastElement = &$array[key($array)];

Answer:

count() will give you the length of the array, which you can apply some simple arithmetic to to get a reference to the last element of the array:

$array = array(
  array('jkl' => '456'),
  array('abc' => '456'),
);
print_r($array);
$last_item = &$array[count($array) - 1];
$last_item['abc'] = '123';
print_r($array);

Answer:

list($last_key,$last_value) = each(array_slice($array,-1,1,true));

Attempt number 2?

$last_item = &$array[array_pop(array_keys($array))];

That gives you a variable reference to the last element of the array.

Leave a Reply

Your email address will not be published. Required fields are marked *