Ryaner
Ryaner

Reputation: 761

Referencing for element in a PHP array

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;
}

Upvotes: 2

Views: 373

Answers (6)

Seb
Seb

Reputation: 25147

$keys = array_keys($array);
echo $array[$keys[0]];

Or you could use the current() function:

reset($array);
$value = current($array);

Upvotes: 5

soulmerge
soulmerge

Reputation: 75704

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

$firstValue = reset($array);
$firstKey = key($array);

Upvotes: 2

Kris
Kris

Reputation: 41827

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.

Upvotes: 1

mdcarter
mdcarter

Reputation: 13

$array = array_values($array);
echo $array[0];

Upvotes: 0

AlexanderJohannesen
AlexanderJohannesen

Reputation: 2028

You can always do ;

$array = array_values($array);

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

Upvotes: 2

cgp
cgp

Reputation: 41381

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.

Upvotes: 0

Related Questions