0

我写了下面的函数来处理一个数组,但它没有返回我 1 认为它的输出 $input[0] 返回我 1。不明白为什么它返回 NULL。我在那种情况下返回的任何东西都返回我 NULL。如果有人知道,请解释一下。谢谢。

function endWithNumber($input)
{
    if (count(array_unique($input)) === 1) {        
        return $input[0];       
    }
    $maxVal = max($input);
    $maxKey = array_search($maxVal,$input);

    foreach ($input as $k => $v) {
        if ($maxKey != $k && $maxVal != $v) {
            $newVal  = ($maxVal - $v);
            $input[$maxKey] = $newVal;
            break;
        }
    }

    endWithNumber($input);
}

$input = array(6,10,15);  
var_dump(endWithNumber($input));
exit;
4

1 回答 1

1

在您的数组计数为 1 之前,您的函数不会返回任何内容。因为您的return语句在if块中。

<?php
function endWithNumber($input)
{
    if (count(array_unique($input)) == 1) 
        return $input[0];       

    $maxVal = max($input);
    $maxKey = array_search($maxVal,$input);

    foreach ($input as $k => $v) 
    {
        if ($maxKey != $k && $maxVal != $v) 
        {
            $newVal  = ($maxVal - $v);
            $input[$maxKey] = $newVal;
            break;
        }
    }   

    return endWithNumber($input);
}

$input = array(6,10,15);  
var_dump(endWithNumber($input));

exit;   
?>
于 2013-06-04T10:42:18.280 回答