w3resource

PHP Exercises: Get the last element of a given list

PHP: Exercise-86 with Solution

Write a PHP program to get the last element of a given list.

Sample Solution:

PHP Code:

<?php
// Function definition for 'last' that takes an array of items as a parameter
function last($items)
{
    // Use 'end' to retrieve the last element of the array
    return end($items);
}

// Call 'last' with an array and display the result using 'print_r'
print_r(last([1, 2, 3]));

// Display a newline
echo "\n";

// Call 'last' with another array and display the result using 'print_r'
print_r(last([2, 1, 3, -4, 5, 1, 2]));
?>

Explanation:

  • Function Definition:
    • The function last is defined to take a single parameter, $items, which is expected to be an array.
  • Retrieve Last Element:
    • Inside the function, end($items) is used to set the internal pointer of the array to its last element and return that element.
  • Example Usage:
    • The function is called with the array [1, 2, 3]:
      • The result (last element 3) is displayed using print_r.
    • A newline is printed for formatting.
  • Second Example Usage:
    • The function is called again with another array [2, 1, 3, -4, 5, 1, 2]:
      • The result (last element 2) is displayed using print_r.
  • Purpose:
    • The last function serves to extract and return the last element of any given array, providing a straightforward way to access the final value.

Output:

3
2

Flowchart:

Flowchart: Get the last element of a given list.

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP program to get the head of a given list.
Next: Write a PHP program to retrieve all of the values for a given key.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/php-basic-exercise-86.php