To get the first element of an array in PHP, you can use the reset
function. This function resets the internal pointer of the array to the first element, and returns the value of the first element.
Here’s an example of how to use the reset
function:
$array = [1, 2, 3];
$first = reset($array);
// $first is now 1
You can also use the array_shift
function to get the first element of the array and remove it from the array. This function shifts the elements of the array to the left, so the second element becomes the first element, the third element becomes the second element, and so on.
Here’s an example of how to use the array_shift
function:
$array = [1, 2, 3];
$first = array_shift($array);
// $first is now 1
// $array is now [2, 3]
If the array is empty, both the reset
and array_shift
functions return null
.
You can also use the key
and current
functions to get the first element of the array without modifying the array. The key
function returns the key of the first element, and the current
function returns the value of the first element.
Here’s an example:
$array = [1, 2, 3];
$key = key($array);
$first = current($array);
// $key is now 0
// $first is now 1
Note that these functions only work with indexed arrays. If you have an associative array, you can use the array_keys
function to get the keys of the array, and then use the reset
or array_shift
function to get the first element.
For example:
$array = ['a' => 1, 'b' => 2, 'c' => 3];
$keys = array_keys($array);
$first_key = reset($keys);
$first_value = $array[$first_key];
// $first_key is now 'a'
// $first_value is now 1