max

(PHP 3, PHP 4, PHP 5)

max -- Находит наибольшее значение

Описание

mixed max ( number arg1, number arg2 [, number ...] )

mixed max ( array numbers )

Возвращает наибольшее из предложенных чисел.

Если в качестве аргументов передан только один - массив чисел, max() возвращает наибольшее из них. Если первый аргумент - integer или float, то обязательно должен быть хотя бы ещё один. В этом случае функция вернёт наибольшее из них. Можно сравнивать неограниченное количество чисел.

Замечание: PHP считает строку, которую не удалось преобразовать в число, как 0, но вернёт саму строку, в случае, если все остальные числа отрицательные. Если указано несколько элементов, эквивалентных 0, max() вернёт первый из них (самый левый).

Пример 1. Примеры использования max()

<?php
echo max(1, 3, 5, 6, 7);  // 7
echo max(array(2, 4, 5)); // 5

echo max(0, 'hello');    // 0
echo max('hello', 0);    // hello
echo max(-1, 'hello');    // hello

// При указании нескольких массивов, они сравниваются полностью
// в нашем примере: 2 == 2, но 4 < 5
$val = max(array(2, 4, 8), array(2, 5, 7)); // array(2, 5, 7)

// При указании массива и отдельных чисел,
// всегда возвращается массив, т.к. он считается самым большим
$val = max('string', array(2, 5, 7), 42);  // array(2, 5, 7)
?>

См также min() и count().



max
johnphayes at gmail dot com
02-May-2006 09:27
Regarding boolean parameters in min() and max():

(a) If any of your parameters is boolean, max and min will cast the rest of them to boolean to do the comparison.
(b) true > false
(c) However, max and min will return the actual parameter value that wins the comparison (not the cast).

Here's some test cases to illustrate:

1.  max(true,100)=true
2.  max(true,0)=true
3.  max(100,true)=100
4.  max(false,100)=100
5.  max(100,false)=100
6.  min(true,100)=true
7.  min(true,0)=0
8.  min(100,true)=100
9.  min(false,100)=false
10. min(100,false)=false
11. min(true,false)=false
12. max(true,false)=true
tim at (NOSPAM) dot crazynot2 dot com
08-Nov-2005 01:56
In response to the previous two posters (zher0 at netcarrier dot com & walkingmantis):

I was trying to do exactly what zher0 suggested; calculate the max value of a multi-dimensional array with variably sized 'sub-arrays'.  Here is a simple little function I came up with to do just that:

<?php
function multimax( $array ) {
  
// use foreach to iterate over our input array.
  
foreach( $array as $value ) {
      
      
// check if $value is an array...
      
if( is_array($value) ) {
          
          
// ... $value is an array so recursively pass it into multimax() to
           // determine it's highest value.
          
$subvalue = multimax($value);
          
          
// if the returned $subvalue is greater than our current highest value,
           // set it as our $return value.
          
if( $subvalue > $return ) {
              
$return = $subvalue;
           }
      
       } elseif(
$value > $return) {
          
// ... $value is not an array so set the return variable if it's greater
           // than our highest value so far.
          
$return = $value;
       }
   }
  
  
// return (what should be) the highest value from any dimension.
  
return $return;
}
?>

Please note that I have only performed very limited testing on this code -- be sure to check it thoroughly if you implement it somewhere!
nonick AT 8027 DOT org
17-Dec-2003 07:50
If you are working with numbers, then you can use:

   $a = ($b > $c) ? $b : $c;

which is somewhat faster (roughly 16%) than

   $a = max($b, $c);

I tested this on several loops using integers and floats, over 1 million iterations.

I'm running PHP 4.3.1 as a module for Apache 1.3.27.
mikhail_kovalev at mail dot ru
13-May-2003 04:32
Note that in version 4.0.3 (the only version I tested):

max (0, 0); // returns 0.
max (0, false); // returns 0.
max (false, 0); // returns false.
max (false, false); // returns false.

As a solution use this:

(int) max (false, 0); // returns 0.
(int) max (false, false); // returns 0.

<logmin>
 Last updated: Tue, 15 Nov 2005