使用 PHP 函数添加 18 到 27 之间的所有偶数

0 php arrays foreach function

我有锻炼要做。需要创建一个函数printRange(),该函数应该接受 2 个数字作为参数,开始和停止。该函数应该将开始和停止(不包括)之间的所有偶数添加到数组中并返回它。使用参数调用函数来回答:18 和 27。在下面编写您的代码并将答案放入变量 ANSWER 中。

需要使用函数因为练习是关于“学习 PHP 中的函数”。

检查下面的代码我来了这么久。

我在想,如果我使用,$x .= $number;那么 PHP 甚至会将 $number 放入,$x=[];但这对我不起作用。答案应该是[20,22,24,26](数组)

$x = [];
function printRange($a, $b) {
    foreach (range($a, $b) as $number) {
        if (0 === $number % 2) {
            $x .= $number;
        }
    }

}


$ANSWER = printRange(18, 27);
Run Code Online (Sandbox Code Playgroud)

我试图删除$x .= $number;并写入 echo $number: 以检查我得到了什么。这就是我得到的1820222426

$x = [];
function printRange($a, $b) {
    foreach (range($a, $b) as $number) {
        if (0 === $number % 2) {
            echo $number;
        }
    }

}




$ANSWER = printRange(18, 27);
Run Code Online (Sandbox Code Playgroud)

Ron*_*den 5

你为什么不使用步骤range()

print_r(range(18, 27, 2));
//Array ( [0] => 18 [1] => 20 [2] => 22 [3] => 24 [4] => 26 ) 
Run Code Online (Sandbox Code Playgroud)