w3resource

PHP Exercises: Get the head of a given list


85. Retrieve the Head of a List

Write a PHP program to get the head of a given list.

Sample Solution:

PHP Code:

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

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

// Display a newline
echo "\n";

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

?>

Explanation:

  • Function Definition:
    • The function head is defined to take a single parameter, $items, which is expected to be an array.
  • Retrieve First Element:
    • Inside the function, reset($items) is used to reset the internal pointer of the array to its first element and return that element.
  • Example Usage:
    • The function is called with the array [1, 2, 3]:
      • The result (first element 1) 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 (first element 2) is displayed using print_r.
  • Purpose:
    • The head function serves to extract and return the first element of any given array, providing a simple way to access the initial value.

Output:

1
2

Flowchart:

Flowchart: Get the head of a given list.

For more Practice: Solve these Related Problems:

  • Write a PHP script to extract and display the first element of an array without modifying the array.
  • Write a PHP function to return the head of a list using basic index access.
  • Write a PHP script to output the initial element from an array while handling empty arrays gracefully.
  • Write a PHP script to retrieve the first value of an array using both manual indexing and built-in functions.

Go to:


PREV : Duplicate Value Checker in a Flat List.
NEXT : Retrieve the Last Element of a List.

PHP Code Editor:



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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.