w3resource

PHP Exercises: Get the head of a given list

PHP: Exercise-85 with Solution

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

Sample Solution: -

PHP Code:

<?php
function head($items)
{
    return reset($items);
}
print_r(head([1, 2, 3]));
echo "\n";
print_r(head([2, 1, 3, -4, 5, 1, 2]));

?>

Sample Output:

1
2

Flowchart:

Flowchart: Get the head 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 check a flat list for duplicate values. Returns true if duplicate values exists and false if values are all unique.
Next: Write a PHP program to get the last element of a given list.

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.

PHP: Tips of the Day

Returns all elements in an array except for the first one

Example:

<?php
function tips_tail($items)
{
  return count($items) > 1 ? array_slice($items, 1) : $items;
}

print_r(tips_tail([1, 5, 7]));
?> 

Output:

Array
(
    [0] => 5
    [1] => 7
)