PHP min and max with an array, is it reliable?

It works, but is it reliable? Will it always work, since MAINarray contains ANOTHERarray, which contains 2 values, and min should work in MAINarray and find the most favorite value in its subarays ....

$a[0]=array(0=>522,1=>'Truck');
$a[1]=array(0=>230,1=>'Bear');
$a[2]=array(0=>13,1=>'Feather');
$a[3]=array(0=>40,1=>'Rabit');
$z=min($a);$y=max($a);
echo "The easiest is ".$z[1]." with only ".$z[0]." pounds!<br>";
echo "The haviest is ".$y[1]." with ".$y[0]." pounds!";

What are you saying?:)

+3
source share
4 answers

My understanding of how it minworks with your input type:

  • Only consider arrays with the least number of elements.
  • Compare first items
  • If there is a relationship, compare the next element of each array. Repeat step.

eg:.

array(
  array(1, "A"),
  array(2),        // min
)


array(
  array(1, "A"),  // min
  array(2, "A"),        
)

array(
  array(1, "Z"),  
  array(1, "A"),  // min
)

I do not have a source for this information, but I remember how it worked.

+2
source

, . , min(array(1, 2, ..., n)) min(1, 2, ..., n), , min :

// With multiple arrays, min compares from left to right
// so in our example: 2 == 2, but 4 < 5
$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)
+3

, . :

function extremes($array, $key=0) {
    if (count($array) === 0) return null;
    $min = $max = null;
    foreach ($array as &$val) {
        if (!isset($val[$key])) continue;
        if ($min > $val[$key]) $min = $val[$key];
        else if ($max < $val[$key]) $max = $val[$key];
    }
    return array($min, $max);
}

$a = array(array(522, 'Truck'), array(230, 'Bear'), array(13, 'Feather'), array(40, 'Rabit'));
list($z, $y) = extremes($a);
+1

The only evidence I can find to say that it is intended to be able to use an array of arrays for comparison is an error report to improve php docs. http://bugs.php.net/bug.php?id=50607

Although, for them it is unlikely to be able to remove this functionality due to the fact that it has to compare arrays, passing in them recursively. Argument variables when using a function are usually an array because there are no finite number of arguments.

0
source

Source: https://habr.com/ru/post/1791866/


All Articles