tags:

views:

267

answers:

6

Answer is not $array[0];

My array is setup as follows

$array = array();
$array[7] =  37;
$array[19] = 98;
$array[42] = 22;
$array[68] = 14;

I'm sorting the array and trying to get the highest possible match out after the sorting. So in this case $array[19] = 98; I only need the value 98 back and it will always be in the first position of the array. I can't reference using $array[0] as the 0 key doesn't exist. Speed constraints mean I can't loop through the array to find the highest match.

There also has to be a better solution than

foreach ( $array as $value )
{
    echo $value;
    break;
}
A: 

If you're sorting it, you can specify your own sorting routine and have it pick out the highest value while you are sorting it.

altCognito
The actual sorting is happening through another part of the system. Effectively a blackbox which I can't control.
Ryaner
Ah yes, then the current() option is the _right_ answer.
altCognito
+2  A: 

You can always do ;

$array = array_values($array);

And now $array[0] will be the correct answer.

AlexanderJohannesen
+4  A: 
$keys = array_keys($array);
echo $array[$keys[0]];

Or you could use the current() function:

reset($array);
$value = current($array);
Seb
+1 for current.
altCognito
You may want to call reset() on the array before current() to make sure you're at the first element, though.
R. Bemrose
Thanks. Current works perfectly. There are other constraints which stop me copying the array or even the indexes. Speed is also a big one in this case.
Ryaner
+3  A: 

You want the first key in the array, if I understood your question correctly:

$firstValue = reset($array);
$firstKey = key($array);
soulmerge
A: 
$array = array_values($array);
echo $array[0];
mdcarter
+1  A: 

If you want the first element you can use array_shift, this will not loop anything and return only the value.

In your example however, it is not the first element so there seems to be a discrepancy in your example/question, or an error in my understanding thereof.

Kris
array_shift() is better than current(), since it doesn't depend on the internal array pointer. If you use next($arr) and then current($arr) it will return a different value. Even though this won't be the case, it's less elegant than array_shift() that _always_ returns the first element.
Emil H
Array_shift will shorten the array. In this case I just need the value to work on before processing the array further in another section of the system.
Ryaner
Ok, valid point. :)
Emil H