Javier Núñez Fernández Full Stack Web Engineer

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:

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:

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 ]] )

3. Example of use


$fruits = array('lemon', 'banana', 'apple', 'orange');
$fruit = current($fruits); // $fruit = 'lemon';
$fruit = next($fruits);    // $fruit = 'banana';
$fruit = current($fruits); // $fruit = 'banana';
$fruit = prev($fruits);    // $fruit = 'lemon';
$fruit = end($fruits);     // $fruit = 'orange';
$fruit = current($fruits); // $fruit = 'orange';
$fruit = reset($fruits); // $fruit = 'lemon';
$fruit = array_pop($fruits); // $fruit = 'orange';
$fruit = array_shift($fruits); // $fruit = 'lemon';

// $fruits = Array ( [0] => banana [1] => apple )