user1540714
user1540714

Reputation: 2089

Finding the smallest value in an array without looping through? (PHP)

I have this array:

$myArray = array("0x40x40" => 64, "0x50x40" => 65, "0x60x40" => 66);

Now I want to find the smalles value, in this case its 64 (the first key/value pair). Is there a way other than looping through the array and to compare the values? The smallest value is not always the first and the values are not sorted by the way.

Thanks!

Upvotes: 1

Views: 1714

Answers (5)

Niels Thiebosch
Niels Thiebosch

Reputation: 147

If you only needs the lowest or highest value

$myArray = array( "0x40x40" => 64, "0x50x40" => 65, "0x60x40" => 66 ); 
asort ( $myArray );
$item = current( $myArray ); 

This is for lowest to highest, in reverse U would need the arsort() function

Upvotes: 0

Sanket R. Patil
Sanket R. Patil

Reputation: 311

will return # array('0x40x40')

$myArray = array(
        "0x40x40" => 64, 
        "0x50x40" => 65, 
        "0x60x40" => 66, 
        );
    array_keys($myArray, min($myArray));  

Upvotes: 0

pinaldesai
pinaldesai

Reputation: 1815

Use below statement in your code and you are done.

min($myArray);

Upvotes: 1

Andreas Wong
Andreas Wong

Reputation: 60594

Using min:

$myArray = array(
    "0x40x40" => 64, "0x50x40" => 65, "0x60x40" => 66, "0x70x40" => 67, "0x80x40" => 68, "0x90x40" => 70, "0x100x40" => 71, "0x110x40" => 74, "0x120x40" => 76);

echo min($myArray);

http://codepad.org/NXhfZpBm

Upvotes: 2

Fluffeh
Fluffeh

Reputation: 33542

You can use the min() function to get your answer nicely.

echo min(2, 3, 1, 6, 7); // 1

or

$myArray=array(2, 3, 1, 6, 7);
echo min($myArray); // 1

Upvotes: 4

Related Questions