php last element of array code example

Example 1: how to get last array element in php

<?php

$source_array = ['key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'];

$result = end($source_array);

echo "Last element: ".$result;

?>

Example 2: php index of last element in array

<?php

$source_array = [
  'key1' => 'value1',
  'key2' => 'value2',
  'key3' => 'value3'
];

echo "Last index: " . array_key_last($source_array);

?>

Example 3: key of last element php

//(PHP 7 >= 7.3.0)
$key = array_key_last($data);

//ALL PHP Versions
end($data);         // move the internal pointer to the end of the array
$key = key($data);  // fetches the key of the element pointed to by the internal pointer

Example 4: php last item of array

echo end(['Gon', 'Killua', 'Hisoka']) // print Hisoka

Example 5: php last element of the array.

<?php
  
// input array
$arr = array('Ram', 'Shita', 'Geeta');
  
// end function print the last
// element of the array.
echo end($arr); 
  
?>

Tags:

Php Example