1

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!

0

5 Answers 5

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

@user1540714 Shhh, don't tell anyone, but so did I. I haven't used that before and a quick google led me to this answer :)
@user1540714 But of course, min() loops through the array. Algorithmically, there's nothing better one can do unless the array has a known structure (sorted ascending/descending, or descending in first part, ascending in second, ...).
2

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

Comments

1

Use below statement in your code and you are done.

min($myArray);

Comments

0

will return # array('0x40x40')

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.