Anda di halaman 1dari 9

PHP: min - Manual Página 1 de 9

Last updated: Fri, 13 May 2011

min
(PHP 4, PHP 5)

min — Encontrar el valor más bajo

Report a bug
Descripción

mixed min ( array $values )

mixed min ( mixed $value1 , mixed $value2 [, mixed $value3... ] )

Si el primer y único parámetro es una matriz, min() devuelve el valor más bajo en esa
matriz. Si al menos dos parámetros son entregados, min() devuelve el menor de estos
valores.

Note:

PHP evaluará un valor string no-numérico como 0 si se compara con un integer,


pero aun devuelve la cadena si ésta es vista como el valor numérico más bajo. Si
varios argumentos evalúan a 0, min() devolverá el valor de cadena alfanumérica
más bajo si se da alguna cadena, o de lo contrario se devuelve un 0 numérico.

Report a bug
Parámetros

valores

Una matriz que contiene los valores.

Report a bug
Valores devueltos

min() devuelve el valor más bajo numéricamente de los parámetros.

Report a bug
Ejemplos

Example #1 Ejemplos de uso de min()

<?php
echo min(2, 3, 1, 6, 7); // 1

file://F:\PHP min - Manual.htm 20/05/2011


PHP: min - Manual Página 2 de 9

echo min(array(2, 4, 5)); // 2

echo min(0, 'hola'); // 0


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

// Con varias matrices, min las compara de izquierda a derecha


// así que en nuestro ejemplo: 2 == 2, pero 4 < 5
$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)

// Si se pasan una matriz y una no-matriz, la matriz nunca


// es devuelta ya que se considera el valor mayor
$val = min('cadena', array(2, 5, 7), 42); // cadena
?>

Report a bug
Ver también

■ max() - Encontrar el valor más alto


■ count() - Cuenta todos los elementos de un array o propiedades de un objecto

User Contributed Notes min


php at keith tyler dot com 23-Nov-2010 09:03

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

matt at borjawebs dot com 13-Nov-2010 09:18

A condensed version (and possible application) of returning an array of array keys


containing the same minimum value:

<?php
// data
$min_keys = array();

file://F:\PHP min - Manual.htm 20/05/2011


PHP: min - Manual Página 3 de 9

$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);
?>

Err 05-Oct-2009 11:32

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
?>

andrew dot j dot dodson at gmail 18-Dec-2008 05:10

min/max works with yyyy-mm-dd dates, e.g.

<?php

$a = array( '2008-10-01', '2008-12-01' );

print min($a); // '2008-10-01'


print max($a); // '2008-12-01'

?>

Which is a unexpected since at the top of this page it says.


"PHP will evaluate a non-numeric string as 0"

And if we cast it as an int then we get the year

<?php
print (int)"2008-01-12"; // 2008
?>

ksours at internetbrands dot com 02-Dec-2008 12:07

PHP_INT_MAX is the MAXINT equivalent

mlester at ndsuk dot com 12-Nov-2008 03:59

I have found a very useful trick to help get round the problem of setting a variable
to max int when finding a min i.e.

<?php
$val = 10;
$min = 100000; // This is unpleasant and I couldn't find a equivalent to the C++
MAXINT
if ($val < $min)
{

file://F:\PHP min - Manual.htm 20/05/2011


PHP: min - Manual Página 4 de 9

$min = $val;
}
?>

try this ...

<?php
$dataSet = Array(7, 8, 9, -1, -100, 0, 1, 2, 3, 5, 6);
$min = true;
$max = true;

foreach ($dataSet as $data )


{
echo("data = $data");
$min = min($data, $min);
$max = max($data, $max);
}

echo("min = $min");
echo("max = $max");
?>

$max can be set to anything e.g. "infinity", but the same trick doesn't work with min,
however true does work (false doesn't). Not sure why though.

The above code even works with a data set like this...
<?php $dataSet = Array("0.5", 1, 2, "3", "-1", "5"); ?>

but min doesn't like null or negative float e.g. "-1.2" and "" can give some odd
results too.

DO 03-Jul-2008 10:23

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;
}
?>

harmor 21-Feb-2008 05:58

A way to bound a integer between two values is:

function bound($x, $min, $max)


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

file://F:\PHP min - Manual.htm 20/05/2011


PHP: min - Manual Página 5 de 9

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

johngreenbury at australianescapes dot com dot au 30-Jan-2008 01:43

You will get an "Wrong parameter count" error (PHP 4 and possibly 5) if your array
looks like the following:

min(115.23,432.11,0.00,45.76)

The 0.00 creates the error. Convert the 0.00 to a high number such as 10000000000.00
or remove it from the array before running the min() function.

piotr_sobolewski at o2 dot nospampleasenono dot pl 07-Nov-2007 04:11

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'));

dave at dtracorp dot com 14-Aug-2006 03:30

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

file://F:\PHP min - Manual.htm 20/05/2011


PHP: min - Manual Página 6 de 9

$minVal = 100;
foreach ($test as $value) {
if (is_numeric($value) && $value < $minVal) {
$minVal = $value;
}

johnphayes at gmail dot com 02-May-2006 04:26

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

steffen at morkland dot com 16-Mar-2006 10:16

> 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 ===

31-Jan-2006 05:37

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 !

DASPRiD ? d [AT] sprid [DOT] de 06-Jul-2005 01:39

Here is my slightly modified version of the bugfree min-version. Now the max()
function is no longer used in the modification and overall it's fasten up. Would be

file://F:\PHP min - Manual.htm 20/05/2011


PHP: min - Manual Página 7 de 9

nice to get some feedback.

<?php
function min_mod () {
$args = func_get_args();

if (!count($args)) return false;


else {
$min = false;
foreach ($args AS $value) {
$curval = floatval($value);
if ($curval < $min || $min === false) $min = $curval;
}
}

return $min;
}
?>

alx5000 at walla dot com 13-Jan-2005 01:16

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
?>

nonick AT 8027 DOT org 24-Jan-2004 03:43

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.

browne at bee why you dot ee dee you 16-Dec-2003 10:30

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);

kieran at mgpenguin dot net 19-Jul-2003 03:28

Further modifications to the minnum function above.. This is for a project where I had
to grab an entire column out of a database consisting of values that might be string,
might be string representations of numbers (floating point or integer) or might be
NULL, and find the minimum NUMERIC value:

function minnum($numarray){

file://F:\PHP min - Manual.htm 20/05/2011


PHP: min - Manual Página 8 de 9

//dont use min(), it contains a bug!


$min=0;
if ( ! is_array($numarray) ) $numarray = func_get_args();
if(is_array($numarray)==true){
$min=max($numarray);
for($z=0;$z<count($numarray);$z++){
$curval=floatval($numarray[$z]);
if(($curval != 0) && ($curval < $min)){
$min=$curval;
}
}
}
return $min;
}

Gets the floating point value of each entry and uses this to check whether it's
actually a number before checking whether it's the minimum or not. Also contains
modifications noted above to use it as a drop in replacement for min - ie multiple
values passed.

Merome at wanadoo dot fr 05-Jul-2003 04:40

Caution : it seems that min() can return a string :

min(";",50)=";" (I expected zero)

calin at php9 dot com 30-May-2003 03:19

if you have an array like this

$arSrc[0]=14;
$arSrc[1]=16;
$arSrc[2]=13;
$arSrc[3]=17;

then in order to get the min element and its position in the array you can do:

$iMinValue = min($arSrc);
$arFlip = array_flip($arSrc);
$iMinPosition = $arFlip[$iMinValue];

echo
'<br />min_value=',
$iMinValue,
'<br />min_position=',
$iMinPosition
;

this example works for also for an associative array; of course with numeric values

08-Jul-2002 09:36

Re: above example - for a proper drop in replacement for the above, insert

if ( ! is_array($numarray) )
$numarray = func_get_args();

after
$min=0;

(For PHP3, check


if (intval(PHP_VERSION) >= 4 && ! is_array($numarray))

file://F:\PHP min - Manual.htm 20/05/2011


PHP: min - Manual Página 9 de 9

$numarray = func_get_args();
)

kevin at pricetrak dot com 08-Apr-2002 06:47

The 'undefined' behaviour can bit you badly. I would expect min(undefined, -1000) to
return -1000. Not so.

nak2 at mail2000 dot ru 14-Mar-2002 07:36

If one of elements is undefided, min() result is underfinded too

Copyright © 2001-2011 The PHP Group


All rights reserved.

file://F:\PHP min - Manual.htm 20/05/2011

Anda mungkin juga menyukai