PHP Maximization function

Discussion in 'Web Design and Development' started by hiddenpremise, Sep 4, 2009.

  1. hiddenpremise macrumors regular

    hiddenpremise

    Joined:
    Jul 25, 2008
    Location:
    Somewhere between my imagination and reality
    #1
    Hi,
    I have an array of objects. Each object has a property that is an int. I want to pick out of the array the object with the max for that particular property. Is there a smart way to do this?

    PHP:
    class example
    {
    public 
    $property;
    private 
    $otherProperty;
    private 
    $yetAnother;
    }

    $array[0] = new example;
    $array[0]->property=10;
    $array[1] = new example;
    $array[1]->property=11;

    (
    example)$maxItem max($array->property)
    //In this example it should return the item at $array[1]

     
  2. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #2
    Here's two ways I can think of.

    PHP:
    // Method 1: Sort array
    usort($array"ExampleSort");
    $max $array[0];
    echo 
    $max->property "<br>"// outputs 11

    // Custom sort, max to min
    function ExampleSort($a$b)
    {
      if (
    $a->property == $b->property) { return 0; }
      if (
    $a->property $b-property) { return -1; }
      else { return 
    1; }
    }

    // Method 2: Loop through
    $max $array[0];
    for (
    $a=1$b=count($array); $a<$b; ++$a) {
      if (
    $array[$a]->property $max->property) { $max $array[$a]; }
    }
    echo 
    $max->property "<br>"// outputs 11
     
  3. Guiyon macrumors 6502a

    Joined:
    Mar 19, 2008
    Location:
    North Shore, MA
    #3
    You could also just run a reduce over the array (my PHP is a bit rusty...):

    Code:
    function rmax( $v, $w )
    {
        $vi = (is_null($v)) ? 0 : $v->property;
        $wi = $w->property;
        
        if( $vi > $wi ) {
            return $v;
        } else {
            return $w;
        }
    }
    
    $max = array_reduce( $array, "rmax", NULL );
    
    echo $max->property . "<br/>";
    Or, if you're running PHP 5.3.0 or higher:
    Code:
    $func = function( $v, $w )
    {
        $vi = (is_null($v)) ? 0 : $v->property;
        $wi = $w->property;
        
        if( $vi > $wi ) {
            return $v;
        } else {
            return $w;
        }
    };
    
    $max = array_reduce( $array, $func, NULL );
    
    echo $max->property . "<br/>";
     
  4. hiddenpremise thread starter macrumors regular

    hiddenpremise

    Joined:
    Jul 25, 2008
    Location:
    Somewhere between my imagination and reality
    #4
    Your replies are greatly appreciated! I ended up using the array_reduce function as I am running 5.3.0.

    Thanks,
    Whit
     

Share This Page