Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder
    Join Date
    Jun 2004
    Posts
    128
    Thanks
    6
    Thanked 0 Times in 0 Posts

    How to get minimum value of an array?

    Trying to get back into coding, and I'm currently working on a new project. Let me get right to the chase.

    Lets say I have an array:
    [3017496] => 15
    [3017678] => 9
    [3017114] => 8
    [3017297] => 10
    [3017428] => 9
    [3017440] => 6
    [3017683] => 5
    [3017306] => 11
    [3017461] => 8
    [3017529] => 6
    [3017683] => 5

    I'm trying to return the minimum values of this array. min() work pretty well, but it only returns an number, and it doesn't discriminate over how many of the lowest value there are.

    Taking that array as an example, min() only returns 5. However, I need this:

    [3017683] => 5
    [3017683] => 5

    I could always just make a foreach function and compare all the values while throwing out ones higher than others until it comes down to what I need, but I wanted to ask here to see if there's already a function to do this.

    Thanks!

  • #2
    Regular Coder FWDrew's Avatar
    Join Date
    Apr 2008
    Location
    Missouri
    Posts
    380
    Thanks
    38
    Thanked 45 Times in 43 Posts
    Not the most elegant solution but will work for what you explained, I'm assuming the values will always be numeric so I set strict comparison to true.

    PHP Code:
    $test_array = array(3017496 => 153017683 => 53017306 => 113017623 => 53017114 => 8);
    $min_val min($test_array);
    $arr_search array_keys($test_array$min_valtrue);
    print_r($arr_search); 
    Dev-Tips.com || Employee at the Envato Network || My Portfolio

  • Users who have thanked FWDrew for this post:

    XtremeGamer99 (09-28-2009)

  • #3
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    PHP Code:
    function min_values( Array $array )
    {
        return
            
    array_intersect_key(
                
    $array,
                
    array_count_values(
                    
    array_keys(
                        
    $array,
                        
    min$array )
                    )
                )
            );
    }

    // usage
    $min_values min_values$values ); 

  • #4
    Regular Coder
    Join Date
    Jun 2004
    Posts
    128
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Thank you all for the help. =)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •