w3resource

PHP Exercises: Return all elements in a given array except for the first one

PHP: Exercise-90 with Solution

Write a PHP program to return all elements in a given array except for the first one.

Sample Solution:

PHP Code:

<?php
// Licence: https://bit.ly/2CFA5XY

// Function definition for 'tail' that takes an array of items as a parameter
function tail($items)
{
    // Use 'count' to check if the array has more than one element
    // If true, use 'array_slice' to return all elements except the first one, otherwise return the original array
    return count($items) > 1 ? array_slice($items, 1) : $items;
}

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

?>

Explanation:

  • Function Definition:
    • The function tail is defined to take one parameter:
      • $items: an array of items.
  • Counting Elements:
    • The function uses count($items) to determine the number of elements in the array.
  • Conditional Logic:
    • If the array has more than one element (count($items) > 1):
      • array_slice($items, 1) is called to return a new array containing all elements except the first one.
      • If the array has one or no elements, the function returns the original array ($items).
  • Purpose:
    • The tail function effectively retrieves all elements of the array except the first, but if the array has only one or no elements, it returns the array as-is.
  • Function Call:
    • The tail function is called with the array [1, 2, 3].
  • Displaying Results:
    • The result of the tail function call is displayed using print_r, which shows the array excluding the first element. In this case, the output will be [2, 3].

Output:

Array
(
    [0] => 2
    [1] => 3
)

Flowchart:

Flowchart: Return all elements in a given array except for the first one.

PHP Code Editor:

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

Previous: Write a PHP program to filter the collection using the given callback.
Next: Write a PHP program to get an array with n elements removed from the beginning of a given array.

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://www.w3resource.com/php-exercises/php-basic-exercise-90.php