Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

hiddenpremise

macrumors regular
Original poster
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]
 
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
 
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/>";
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.