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:
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:
Use the PHP
array_values()FunctionIf you know the exact index or key of an array you can easily get the first element, like this:
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:
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:
need an explanation for this answer? contact us directly to get an explanation for this answer