首頁  >  文章  >  後端開發  >  php求數組中的最大值

php求數組中的最大值

(*-*)浩
(*-*)浩原創
2019-09-20 09:32:083467瀏覽

php求數組中的最大值

max

(PHP 4, PHP 5, PHP 7)

max — 找出最大值

說明 (建議學習:PHP程式設計從入門到精通

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

如果只有一個參數且為數組,max() 會傳回該數組中最大的值。如果第一個參數是整數、字串或浮點數,則至少需要兩個參數而 max() 會傳回這些值中最大的一個。可以比較無限多個值。

Note:

PHP 會將非數值的 string 當成 0,但如果這個正是最大的數值則仍然會傳回一個字串。如果多個參數都求值為 0 且是最大值,max() 會傳回其中數值的 0,如果參數中沒有數值的 0,則傳回按字母表順序最大的字串。

參數 

values

包含了多個值的陣列。

傳回值 

max() 傳回參數中數值最大的值。

使用 max() 的範例

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

// When &#39;hello&#39; is cast as integer it will be 0. Both the parameters are equally
// long, so the order they are given in determines the result
echo max(0, &#39;hello&#39;);     // 0
echo max(&#39;hello&#39;, 0);     // hello

echo max(&#39;42&#39;, 3); // &#39;42&#39;

// Here 0 > -1, so &#39;hello&#39; is the return value.
echo max(-1, &#39;hello&#39;);    // 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)

// 对多个数组,max 从左向右比较。
   // 因此在本例中:2 == 2,但 4 < 5
$val = max(array(2, 4, 8), array(2, 5, 7)); // array(2, 5, 7)

// 如果同时给出数组和非数组作为参数,则总是将数组视为
   // 最大值返回
$val = max(&#39;string&#39;, array(2, 5, 7), 42);   // array(2, 5, 7)
?>

以上是php求數組中的最大值的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn