How can i display the first element of an array in php?

This is not so simple response in the real world. Suppose that we have these examples of possible responses that you can find in some libraries.

$array1 = array();
$array2 = array(1,2,3,4);
$array3 = array('hello'=>'world', 'foo'=>'bar');
$array4 = null;

var_dump('reset1', reset($array1));
var_dump('reset2', reset($array2));
var_dump('reset3', reset($array3));
var_dump('reset4', reset($array4)); // Warning

var_dump('array_shift1', array_shift($array1));
var_dump('array_shift2', array_shift($array2));
var_dump('array_shift3', array_shift($array3));
var_dump('array_shift4', array_shift($array4)); // Warning

var_dump('each2', each($array1));
var_dump('each2', each($array2));
var_dump('each3', each($array3));
var_dump('each4', each($array4)); // Warning

var_dump('array_values1', array_values($array1)[0]); // Notice
var_dump('array_values2', array_values($array2)[0]);
var_dump('array_values3', array_values($array3)[0]);
var_dump('array_values4', array_values($array4)[0]); // Warning

var_dump('array_slice1', array_slice($array1, 0, 1));
var_dump('array_slice2', array_slice($array2, 0, 1));
var_dump('array_slice3', array_slice($array3, 0, 1));
var_dump('array_slice4', array_slice($array4, 0, 1)); // Warning

list($elm) = $array1; // Notice
var_dump($elm);
list($elm) = $array2;
var_dump($elm);
list($elm) = $array3; // Notice
var_dump($elm);
list($elm) = $array4;
var_dump($elm);

Like you can see, we have several 'one line' solutions that work well in some cases, but not in all.

In my opinion, you have should that handler only with arrays.

Now talking about performance, assuming that we have always array, like this:

$elm = empty($array) ? null : ...($array);

...you would use without errors:
$array[count($array)-1];
array_shift
reset
array_values
array_slice

array_shift is faster than reset, that is more fast than [count()-1], and these three are faster than array_values and array_slice.

Topic: PHP / MySQLPrev|Next

Answer: Use the PHP array_values() Function

If you know the exact index or key of an array you can easily get the first element, like this:

<?php
// A sample indexed array
$cities = array("London", "Paris", "New York");
echo $cities[0]; // Outputs: London
 
// A sample associative array
$fruits = array("a" => "Apple", "b" => "Ball", "c" => "Cat");
echo $fruits["a"]; // Outputs: Apple
?>

However, there are certain situations where you don't know the exact index or key of the first element. In that case you can use the array_values() function which returns all the values from the array and indexes the array numerically, as shown in the following example:

<?php
$arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat");
echo array_values($arr)[0]; // Outputs: Apple
?>

Alternativly, you can also use the reset() function to get the first element.

The reset() function set the internal pointer of an array to its first element and returns the value of the first array element, or FALSE if the array is empty.

You can also use the current() function to get the first element of an array. This function returns the current element in an array, which is the first element by default unless you've re-positioned the array pointer, otherwise use the reset() function. Here's an example:

<?php
$arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat");
echo current($arr); // Outputs: Apple
echo reset($arr); // Outputs: Apple
echo next($arr); // Outputs: Ball
echo current($arr); // Outputs: Ball
echo reset($arr); // Outputs: Apple
?>


Here are some more FAQ related to this topic:

  • How to extract substring from a string in PHP
  • How to combine two strings in PHP
  • How to convert a string to uppercase in PHP

In this article, we will see how to get access to the first element of an array in PHP, & also understand their implementation through the examples. There are mainly 3 types of arrays in PHP that can be used to fetch the elements from the array:

  • Indexed Array: It is an array with a numeric key. It is basically an array wherein each of the keys is associated with its own specific value.
  • Associative Array: It is used to store key-value pairs.
  • Multidimensional Array: It is a type of array which stores another array at each index instead of a single element. In other words, define multi-dimensional arrays as array of arrays. 

There are several methods to get the first element of an array in PHP. Some of the methods are using foreach loop, reset function, array_slice function, array_values, array_reverse, and many more. We will discuss the different ways to access the first element of an array sequentially.

By direct accessing the 0th index:

PHP

<?php

  $array = array('geeks', 'for', 'computer');

  echo $array[0];

?>

Output:

geeks

Using foreach loop: The foreach construct works on both array and objects. The foreach loop iterates over an array of elements, the execution is simplified and finishes the loop in less time comparatively.

Syntax:

foreach( $array as $key => $element) {
    // PHP Code to be executed
}

Example: This example illustrates the foreach loop in PHP.

PHP

<?php 

  $array = array(

      33 => 'geeks'

      36 => 'for'

      42 => 'computer'

  );

  foreach($array as $name) {

      echo $name;

      break

  }

?>

Output:

geeks

Using reset() function: The reset() function is used to move the array’s internal pointer to the first element.

Syntax:

reset($array)

Example: This example illustrates the use of the reset() function that helps to move any array’s internal pointer to the first element of that array.

PHP

<?php 

  $array = array(

      33 => 'geeks'

      36 => 'for'

      42 => 'computer'

  );

  echo reset($array);

?>

Output:

geeks

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

Syntax:

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

Example: This example illustrates the array_slice() Function to fetch a part of an array by slicing through it, according to the user’s choice.

PHP

<?php

  $array = array(

      33 => 'geeks'

      36 => 'for'

      42 => 'computer'

  );

  echo array_slice($array, 0, 1)[0];

?>

Output:

geeks

Using array_values() function: This function return an array of values from another array that may contain key-value pairs or just values.

Syntax:

array array_values ( array $array )

Example: This example describes the use of the array_values() function.

PHP

<?php

  $array = array(

      33 => 'geeks'

      36 => 'for'

      42 => 'computer'

  );

  echo array_values($array)[0];

?>

Output:

geeks

Using array_pop() function: This function pop the element off the end of the array.

Syntax:

mixed array_pop ( array &$array )

By default, the array_reverse() function will reset all numerical array keys to start counting from zero while literal keys will remain unchanged unless a second parameter preserve_keys is specified as TRUE. This method is not recommended as it may do unwanted longer processing on larger arrays to reverse them prior to getting the first value.

Example: This example describes the use of the array_pop function.

PHP

<?php

    $array = array(

        33 => 'geeks',

        36 => 'for',

        42 => 'computer'

    );

    $arr = array_reverse($array);

    echo array_pop($arr);

?>

Output:

geeks

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.


How can we get the first element of an array in PHP?

There are several methods to get the first element of an array in PHP. Some of the methods are using foreach loop, reset function, array_slice function, array_values, array_reverse, and many more.

How do I print the first element of an array?

Alternativly, you can also use the reset() function to get the first element. The reset() function set the internal pointer of an array to its first element and returns the value of the first array element, or FALSE if the array is empty.

How do you access the first element of an array?

The first and last elements are accessed using an index and the first value is accessed using index 0 and the last element can be accessed through length property which has one more value than the highest array index. The array length property in JavaScript is used to set or return the number of elements in an array.

How do you print the first and last element of an array in PHP?

$firstEle = reset($arr); reset() rewinds array's internal pointer to the first element and returns the value of the first array element. And end() to get the last: $lastEle = end($arr);