1

I have this array :

$fr_coin_multiplier_asc = array('BTC'=>30, 
                                'ETH'=>28, 
                                'BNB'=>36, 
                                'USDT'=>39,
                                'NEO'=>8, 
                                'LTC'=>9, 
                                'BCC'=>17);
asort($fr_coin_multiplier_asc);

and I want to get the first element of that array after sorted using this method :

reset($fr_coin_multiplier_asc);
print_r(current($fr_coin_multiplier_asc));

in this case, i'm expecting NEO and 8 as result, but it only gives me 8. how to get NEO and also 8?

thank you

1
  • Use key($array) Commented Jun 30, 2018 at 17:57

5 Answers 5

7

Try using key($fr_coin_multiplier_asc). Per the PHP documentation:

key() returns the index element of the current array position.

Sign up to request clarification or add additional context in comments.

Comments

1

Modern answer (PHP >= 7.3):

array[ array_key_first( $array ) ]

See https://www.php.net/manual/en/function.array-key-first.php

Comments

0

Try this construction

key($fr_coin_multiplier_asc) . ' => ' . current($fr_coin_multiplier_asc);

It return key and value from array. Hope it's help for you

Comments

0

Here we try to display the array content after the sorting, but we break after we get the first one !

$fr_coin_multiplier_asc = array('BTC'=>30, 
                                'ETH'=>28, 
                                'BNB'=>36, 
                                'USDT'=>39,
                                'NEO'=>8, 
                                'LTC'=>9, 
                                'BCC'=>17);
asort($fr_coin_multiplier_asc);
reset($fr_coin_multiplier_asc);
print_r(current($fr_coin_multiplier_asc));
echo "<br>";
foreach($fr_coin_multiplier_asc as $x => $x_value) {
    echo $x.":".$x_value;
    break;  
}

In this case the output will be : NEO:8

Comments

-1

With PHP 5.4+ (but might cause an index error if empty so I use the fallback ??):

\array_values($array)[0] ?? null;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.