PHP Conference Kansai 2025

Voting

: nine plus zero?
(Example: nine)

The Note You're Voting On

ar at xonix dot ch
14 years ago
If you need the first or last entry of an array, then this could help you.

<?php
function array_last_entry($arr){
if(!
is_array($arr))
return;

if(empty(
$arr))
return;

return
end($arr);
}

function
array_first_entry($arr){
if(!
is_array($arr))
return;

if(empty(
$arr))
return;

reset($arr);
return
current($arr);
}

$arr = array( '5' => 'five', '3' => 'three', '8' => 'eight',);

echo
'last entry: '.array_last_entry($arr).'<br>';

echo
'first entry: '.array_first_entry($arr).'<br>';

echo
'alternative output:<br>';

echo
'last entry: '.$arr[count($arr)-1];

echo
'<br>first entry: '.$arr[0];
?>

The output will look like:
last entry: eight
first entry: five
alternative output:
last entry:
first entry:

As you can see, if you have to handle arrays with non-continuous indexes, these functions may be very helpful.

<< Back to user notes page

To Top