在PHP中遍历一个数组,而不使用count和sizeof函数


Iterate through an an array in PHP without using count and sizeof function

我的任务是创建一个名为"maximum"的函数,该函数将在给定的一组数字中找到最大值。我的函数应该返回最大值。

要求:

我的函数不应使用对数组中元素数量进行计数的"sizeof"或"count"函数。我该怎么做?这是我的PHP函数:

function maximum($array){
    $elements = count($array);
    $max = $array[0];
    for($a=1; $a < $elements; $a++){
        if ($max < $array[$a]){
            $max =  $array[$a];
        }
    }
    return $max;
} 

使用内置函数:

$max = max($array);

使用foreach:

$max = 0;
foreach ( $array as $item ) {
    if ( $max<$item ) {
        $max = $item;
    }
}

使用排序功能:

rsort($array);
$max = array_shift($array);

sort($array);
$max = array_pop($array);
$max = $array[0];
foreach ($array as $value) {
    if ($max < $value){
        $max =  $value;
    }
}

您可以通过max()来完成此操作

echo max($array);
function maximum($array) {
  $max = 0;
  foreach($array as $value) { // get every value of array
    if($max < $value) // if value of array is bigger then last one
      $max = $value; // put it into $max
  }
  return $max;
}