Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing for element in a PHP array

Tags:

arrays

php

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;
}
like image 671
Ryaner Avatar asked Dec 07 '25 12:12

Ryaner


1 Answers

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

Or you could use the current() function:

reset($array);
$value = current($array);
like image 199
Seb Avatar answered Dec 10 '25 01:12

Seb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!