min

(PHP 4, PHP 5)

minНаходит наименьшее значение

Описание

mixed min ( array $values )
mixed min ( mixed $value1 , mixed $value2 [, mixed $... ] )

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

Замечание:

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

Список параметров

values

Массив содержащий значения.

value1

Любое поддающееся сравнению значение.

value2

Любое поддающееся сравнению значение.

...

Любое поддающееся сравнению значение.

Возвращаемые значения

Функция min() возвращает наименьшее числовое значение из значений параметра.

Примеры

Пример #1 Пример использования min()

<?php
echo min(23167);  // 1
echo min(array(245)); // 2

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

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

// При указании массива и не массива, 
// первый никогда не возвращается, т.к. считается самым большим
$val min('string', array(257), 42);   // string
?>

Смотрите также

  • max() - Возвращает наибольшее значение
  • count() - Подсчитывает количество элементов массива или что-то в объекте

Коментарии

min() can be used to cap values at a specific value. For instance, if you're grading papers and someone has some extra credit, but  that shouldn't make it to the final score:

$pts_possible = 50;
$score = 55;

// Percent will equal 1 if $score/$pts_possible is greater than 1
$percent = min($score/$pts_possible,1);
2003-12-16 16:30:13
http://php5.kiev.ua/manual/ru/function.min.html
I tested this with max(), but I suppose it applies to min() too: If you are working with numbers, then you can use:
 
    $a = ($b < $c) ? $b : $c;
 
 which is somewhat faster (roughly 16%) than
 
    $a = min($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.
2004-01-24 09:43:37
http://php5.kiev.ua/manual/ru/function.min.html
If you want min to return zero (0) when comparing to a string, try this:

<?php
min
(3,4,";");  // ";"
min(0,min(3,4,";")) // 0
?>
2005-01-12 19:16:09
http://php5.kiev.ua/manual/ru/function.min.html
Автор:
NEVER EVER use this function with boolean variables !!!
Or you'll get something like this: min(true, 1, -2) == true;

Just because of:
min(true, 1, -2) == min(min(true,1), -2) == min(true, -2) == true;

You are warned !
2006-01-31 11:37:24
http://php5.kiev.ua/manual/ru/function.min.html
> NEVER EVER use this function with boolean variables !!!
> Or you'll get something like this: min(true, 1, -2) == true;

> Just because of:
> min(true, 1, -2) == min(min(true,1), -2) == min(true, -2) == true;

It is possible to use it with booleans, there is is just one thing, which you need to keep in mind, when evaluating using the non strict comparison (==) anyting that is not bool false, 0 or NULL is consideret true eg.:
(5 == true) = true;
(0 == true) = false;
true is also actually anything else then 0, false and null. However when true is converted to a string or interger true == 1, therefore when sorting true = 1. But if true is the maximum number bool true is returned. so to be sure, if you only want to match if true is the max number remember to use the strict comparison operater ===
2006-03-16 04:16:46
http://php5.kiev.ua/manual/ru/function.min.html
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
2006-05-02 12:26:54
http://php5.kiev.ua/manual/ru/function.min.html
empty strings '' will also return false or 0, so if you have something like

$test = array('', 1, 5, 8, 44, 22);

'' will be returned as the lowest value

if you only want to get the lowest number, you'll have to resort to the old fashioned loop

// default minimum value
$minVal = 100;
foreach ($test as $value) {
if (is_numeric($value) && $value < $minVal) {
$minVal = $value;
}
2006-08-13 23:30:49
http://php5.kiev.ua/manual/ru/function.min.html
Be very careful when your array contains both strings and numbers. This code works strange (even though explainable) way:
var_dump(max('25.1.1', '222', '99'));
var_dump(max('2.1.1', '222', '99'));
2007-11-07 10:11:57
http://php5.kiev.ua/manual/ru/function.min.html
Автор:
A way to bound a integer between two values is:

function bound($x, $min, $max)
{
     return min(max($x, $min), $max);
}

which is the same as:

$tmp = $x;
if($tmp < $min)
{
    $tmp = $min;
}
if($tmp > $max)
{
     $tmp = $max;
}
$y = $tmp;

So if you wanted to bound an integer between 1 and 12 for example:

Input:
$x = 0;
echo bound(0, 1, 12).'<br />';
$x = 1;
echo bound($x, 1, 12).'<br />';
$x = 6;
echo bound($x, 1, 12).'<br />';
$x = 12;
echo bound($x, 1, 12).'<br />';
$x = 13;
echo bound($x, 1, 12).'<br />';

Output:
1
1
6
12
12
2008-02-21 11:58:49
http://php5.kiev.ua/manual/ru/function.min.html
Автор:
I've modified the bugfree min-version to ignore NULL values (else it returns 0).

<?php
function min_mod () {
 
$args func_get_args();
 
  if (!
count($args[0])) return false;
  else {
   
$min false;
    foreach (
$args[0] AS $value) {
      if (
is_numeric($value)) {
       
$curval floatval($value);
        if (
$curval $min || $min === false$min $curval;
      }
    }
  }
 
  return 
$min;   
}
?>
2008-07-03 06:23:46
http://php5.kiev.ua/manual/ru/function.min.html
Автор:
When using a variable with an array that has a list of numbers, put just the variable in min(). Don't use integer index's. Seems pretty straight forward now, but I wasn't used to just putting down the variable for an array in functions.

<?php
  $list 
= array(9,5,4,6,2,7);
  echo 
min($list); // display 2
?>
2009-10-05 07:32:58
http://php5.kiev.ua/manual/ru/function.min.html
A condensed version (and possible application) of returning an array of array keys containing the same minimum value:

<?php
// data
$min_keys = array();
$player_score_totals = array(
'player1' => 300,
'player2' => 301,
'player3' => 302,
'player4' => 301,
...
);

// search for array keys with min() value
foreach($player_score_totals as $playerid => $score)
    if(
$score == min($player_score_totals)) array_push($min_keys$playerid);

print_r($min_keys);
?>
2010-11-13 15:18:08
http://php5.kiev.ua/manual/ru/function.min.html
If NAN is the first argument to min(), the second argument will always be returned.

If NAN is the second argument, NAN will always be returned.

The relationship is the same but inverted for max().

<?php
// \n's skipped for brevity
print max(0,NAN);
print 
max(NAN,0);
print 
min(0,NAN);
print 
min(NAN,0);
?>

Returns:
0
NAN
NAN
0
2010-11-23 15:03:47
http://php5.kiev.ua/manual/ru/function.min.html
Here is function can find min by array key

<?php
function min_by_key($arr$key){
   
$min = array();
    foreach (
$arr as $val) {
        if (!isset(
$val[$key]) and is_array($val)) {
           
$min2 min_by_key($val$key);
           
$min[$min2] = 1;
        } elseif (!isset(
$val[$key]) and !is_array($val)) {
            return 
false;
        } elseif (isset(
$val[$key])) {
           
$min[$val[$key]] = 1;
        }
    }
    return 
minarray_keys($min) );
}
?>
2011-09-26 03:35:15
http://php5.kiev.ua/manual/ru/function.min.html
Автор:
A function that returns the lowest integer that is not 0.
<?php
/* like min(), but casts to int and ignores 0 */
function min_not_null(Array $values) {
    return 
min(array_diff(array_map('intval'$values), array(0)));
}
?>
2013-10-13 19:09:43
http://php5.kiev.ua/manual/ru/function.min.html
min() (and max()) on DateTime objects compares them like dates (with timezone info) and returns DateTime object.
<?php 
$dt1 
= new DateTime('2014-05-07 18:53', new DateTimeZone('Europe/Kiev'));
$dt2 = new DateTime('2014-05-07 16:53', new DateTimeZone('UTC'));
echo 
max($dt1,$dt2)->format(DateTime::RFC3339) . PHP_EOL// 2014-05-07T16:53:00+00:00
echo min($dt1,$dt2)->format(DateTime::RFC3339) . PHP_EOL// 2014-05-07T18:53:00+03:00
?>

It works at least 5.3.3-7+squeeze17
2014-05-07 19:10:35
http://php5.kiev.ua/manual/ru/function.min.html
Автор:
A min_by function:
<?php
function min_by(Array $arr, Callable $func){
   
$mapped array_map($func$arr);
    return 
$arr[array_search(min($mapped), $mapped)];
}
$a = ["albatross""dog""horse"];
echo 
min_by($a"strlen"); // dog
?>
2017-04-19 18:21:59
http://php5.kiev.ua/manual/ru/function.min.html

    Поддержать сайт на родительском проекте КГБ