tags:

views:

153

answers:

5

Hi !

I have an array:

array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )

I would like to get first element of this array. Expected result: string apple

One requirement: it cannot be done with passing by reference, so array_shift is not good solution.

Any ideas ?

+3  A: 
$arr = $array = array( 9 => 'apple', 7 => 'orange', 13 => 'plum' );
reset($arr);
echo current($arr); // echoes 'apple'

if you don't want to loose the current pointer position, just create an alias for the array.

yoda
Reference, sory mate.
hsz
didn't get it, what do you mean? It works fine whether the key of the first is bigger than the other ones.
yoda
+1  A: 

kludgy answer:

$foo = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );

function get_first ($foo) {
    foreach ($foo as $k=>$v){
     return $v;
    }
}

print get_first($foo);
William Macdonald
+1  A: 

can be done this way too:

$array = array(1, 2, 3, 4, 5);
$output = array_slice($array, 1);
print_r ($output);
Sarfraz
+1  A: 

I think using array_values would be your best bet here. You could return the value at index zero from the result of that function to get 'apple'.

jmking
+1  A: 
array_shift(array_values($array));
blueyed