Get the first element of an array in PHP
Problem Statement: How to access the first element of an array in PHP?
Solution: There are mainly three types of arrays in PHP:
Indexed Array
Associative Array
Multidimensional Array
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.
<?php
// PHP program to access the first
// element of the array
$array = array('hellod', 'for', 'computer');
echo $array[0]
?>
Output:
hellod
2. Using foreach loop:
<?php
// PHP program to access the first
// element of the array
$array = array(
33 => 'coderfundatk',
36 => 'for',
42 => 'computer'
);
foreach($array as $name) {
echo $name;
// break loop after first iteration
break;
}
?>
Output:
coderfundatk
3. Using array_slice() function: array_slice() returns the sequence
of elements from the array as specified by the offset and length parameters.
Syntax:
<?php
// PHP program to access the first
// element of the array
$array = array(
33 => 'coderfundatk',
36 => 'for',
42 => 'computer'
);
echo array_slice($array, 0, 1)[0];
?>
Output:
coderfundatk
4. Using array_values() function: This function return
all the values of an array.
Syntax:
<?php
// PHP program to access the first
// element of the array
$array = array(
33 => 'geeks',
36 => 'for',
42 => 'computer'
);
echo array_values($array)[0];
?>
5. Using array_pop() function: This function pop
the element off the end of array.
Syntax:
<?php
// PHP program to access the first
// element of the array
$array = array(
33 => 'geeks',
36 => 'for',
42 => 'computer'
);
echo array_pop(array_reverse($array));
?>