I have an array:
array( 4 => \'apple\', 7 => \'orange\', 13 => \'plum\' )
I would like to get the first element of this array. Expect
$myArray = array (4 => 'apple', 7 => 'orange', 13 => 'plum');
$arrayKeys = array_keys($myArray);
// The first element of your array is:
echo $myArray[$arrayKeys[0]];
Two solutions for you.
Solution 1 - Just use the key. You have not said that you can not use it. :)
<?php
// Get the first element of this array.
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
// Gets the first element by key
$result = $array[4];
// Expected result: string apple
assert('$result === "apple" /* Expected result: string apple. */');
?>
Solution 2 - array_flip() + key()
<?php
// Get first element of this array. Expected result: string apple
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
// Turn values to keys
$array = array_flip($array);
// You might thrown a reset in just to make sure
// that the array pointer is at the first element.
// Also, reset returns the first element.
// reset($myArray);
// Return the first key
$firstKey = key($array);
assert('$firstKey === "apple" /* Expected result: string apple. */');
?>
Solution 3 - array_keys()
echo $array[array_keys($array)[0]];
A kludgy way is:
$foo = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
function get_first ($foo) {
foreach ($foo as $k=>$v){
return $v;
}
}
print get_first($foo);
I don't like fiddling with the array's internal pointer, but it's also inefficient to build a second array with array_keys()
or array_values()
, so I usually define this:
function array_first(array $f) {
foreach ($f as $v) {
return $v;
}
throw new Exception('array was empty');
}
current($array)
can get you the first element of an array, according to the PHP manual.
Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array.
So it works until you have re-positioned the array pointer, and otherwise you'll have to reset the array using reset()
No one has suggested using the ArrayIterator class:
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
$first_element = (new ArrayIterator($array))->current();
echo $first_element; //'apple'
gets around the by reference stipulation of the OP.