Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP min and max with array, is it reliable?

Tags:

arrays

php

logic

This works but, is it reliable? Will it always work since the MAINarray is containing ANOTHERarray which contains 2 values and min should work in MAINarray and find lowest 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 heaviest is ".$y[1]." with ".$y[0]." pounds!";

What you say?

like image 269
FeRtoll Avatar asked Mar 09 '26 04:03

FeRtoll


2 Answers

Yes, it is reliable. It's safe to assume that min(array(1, 2, ..., n)) is equivalent to min(1, 2, ..., n), and the documentation specifically covers how min compares multiple arrays:

// 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)
like image 177
meagar Avatar answered Mar 11 '26 20:03

meagar


My understanding of how min works with your type of input is:

  1. Only consider the arrays with the fewest number of items.
  2. Compare the first elements
  3. If there is a tie, compare the next element of each array. Repeat step.

e.g.:

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


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

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

I don't have a source for that information, but it's how I remember it working.

like image 22
Matthew Avatar answered Mar 11 '26 20:03

Matthew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!