PHP: Get first element of array without removing it

1. Introduction

In this article I will explain some methods to solve this problem: how to get the first (or last) element of an array without removing it.

2. Explanation

If we execute these two PHP functions:

  • array_pop, a function that get the last element of an array and remove it
  • array_shift, a function that get the first element of an array and remove it

The element that we get will be removed from the array, but sometimes we just want to get an element without removing it from the array.

Here we have the different methods we have to do this:

2.1. Use of current and end function

We have different functions to get different elements from an array:

  • current($array)
    that will return the element from the pointer. If we haven’t moved the pointer, then it will return the first element.
  • end($array)
    that will move the pointer to the last element and then return it
  • next($array) and prev($array)
    will move the pointer in the array to the next or the previous position.

To understand this, let’s see an example

2.2. Use of array_slice

This function get a sequence of elements of an array but doesn’t modify the array itself. This function accept at least two arguments:

array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )

  • $array is the array
  • $offset indicates the elements that will be returned from the array. If offset is positive, the sequence will start at that position. If is negative, the sequence will start that far from the end of the $array.

3. Example of use



Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.