max

(PHP 4, PHP 5, PHP 7, PHP 8)

max找出最大值

说明

max(mixed $value, mixed ...$values): mixed

替代签名(不支持命名参数):

max(array $value_array): mixed

如果仅有一个参数且为数组,max() 返回该数组中最大的值。如果第一个参数是整数、字符串或浮点数,则至少需要两个参数而 max() 会返回这些值中最大的一个。可以比较无限多个值。

注意:

不同类型的值将使用标准比较规则进行比较。例如,一个非数字 stringint 比较时就当做是 0,但多个非数字 string 值将会按照字母数字比较。返回的实际值是未应用任何转换的原始类型。

警告

传递不同类型的参数时要小心,因为 max() 会产生不可预测的结果。

参数

value

任何可比较的值。

values

任何可比较的值。

value_array

包含值的数组。

返回值

max() 根据标准比较返回认为是“最大”的参数值。如果不同类型的多个值认为相等(比如 0'abc'),则将会返回提供给函数的第一个值。

错误/异常

如果传递空数组,max() 抛出 ValueError

更新日志

版本 说明
8.0.0 max() 现在失败时会抛出 ValueError;之前会返回 false 并发出 E_WARNING 错误。

范例

示例 #1 使用 max() 的例子

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

// The string 'hello' when compared to an int is treated as 0
// Since the two values are equal, the order they are provided determines the result
echo max(0, 'hello'); // 0
echo max('hello', 0); // hello

// Here we are comparing -1 < 0, so 'hello' is the highest value
echo max('hello', -1); // hello

// With multiple arrays of different lengths, max returns the longest
$val = max(array(2, 2, 2), array(1, 1, 1, 1)); // array(1, 1, 1, 1)

// Multiple arrays of the same length are compared from left to right
// so in our example: 2 == 2, but 5 > 4
$val = max(array(2, 4, 8), array(2, 5, 1)); // array(2, 5, 1)

// 如果同时给出数组和非数组,则绝对不会返回数组
// 因为比较认为数组大于任何值
$val = max('string', array(2, 5, 7), 42); // array(2, 5, 7)

// If one argument is NULL or a boolean, it will be compared against
// other values using the rule FALSE < TRUE regardless of the other types involved
// In the below example, -10 is treated as TRUE in the comparison
$val = max(-10, FALSE); // -10

// 0, on the other hand, is treated as FALSE, so is "lower than" TRUE
$val = max(0, TRUE); // TRUE
?>

参见

  • min() - 找出最小值
  • count() - 统计数组、Countable 对象中所有元素的数量

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top