How to get the first element of an array in PHP?

In this article we will discuss how to get the first element of an array in PHP. There are many ways to get the first element of an array in PHP.

Get the first element of an array in PHP

We are using several method like direct accessing the 0th index, foreach loop, reset() function, array_shift() function, array_slice() function and array_values() to get the first element of an array.

Method #1 By direct accessing the 0th index:

<?php
$stack_array = array( 'code', 'developer','programming', 'blog');
echo $stack_array[0];
?>

The above example will output:

code

Method #2 Using foreach loop

<?php
$stack_array = array( 'code', 'developer','programming', 'blog');

$max_loop    = 1; //this is the desired value of looping
$count       = 0; //first we set the count to be zero
foreach ($stack_array as $key => $value) {
    echo $value;
    $count++; //increase the value of the count by 1
    if ($count == $max_loop) { //break the loop is count is equal to the max_loop
        break;
    }
}
?>

The above example will output:

code

Method #3 Using reset() function

The reset() function moves the internal pointer to the first element of the array and returns the value of the first array element.

Syntax

reset(array)

<?php 
$stack_array = array( 'code', 'developer','programming', 'blog');
echo reset($stack_array);
?>

The above example will output:

code

Method #4 Using array_shift() function

The array_shift() function removes the first element from an array, and returns the value of the removed element.

Syntax

array_shift(array)

<?php
$stack_array = array( 'code', 'developer','programming', 'blog');
$first_element = array_shift($stack_array);
echo $first_element;
?>

The above example will output:

code

Method #5 Using array_slice() function

The array_slice() function returns the sequence of elements from the array as specified by the offset and length parameters.

Syntax

array_slice(array,start,length,preserve)

<?php 
$stack_array = array( 'code', 'developer','programming', 'blog');
$first_element = array_slice($stack_array, 0, 1);
echo $first_element[0];
?>

The above example will output:

code

Method #6 Using array_values() function

The array_values() function returns an array containing all the values of an array. The returned array will have numeric keys, starting at 0 and increase by 1.

Syntax

array_values(array)

<?php 
$stack_array = array( 'code', 'developer','programming', 'blog');
$first_element = array_values($stack_array);
echo $first_element[0];
?>

The above example will output:

code

Leave A Reply

Your email address will not be published.