将整数推入数组的问题

时间:2014-09-25 20:39:33

标签: php arrays

我一直在努力解决Project Euler问题1,我觉得我缺少一些基本的东西。你能帮我解决一下我的错误吗?

我先试了这个:

<?php
/* 
** Project Euler Problem 1
** If we list all the natural numbers below 10 that are multiples of 3 or 5,
** we get 3, 5, 6 and 9. The sum of these multiples is 23. 
** Find the sum of all the multiples of 3 or 5 below 1000.
*/
$numberOne = 3;
$numberTwo = 5;
$endingIndex = 1000;
$multiplesOfNumbers = array();  

for ($index = 1; $index <= $endingIndex; $index++) {
    if ($index % $numberOne == 0 && $index % $numberTwo == 0) {
        $multipleOfNumbers[] = $index;
    }
}
echo $multiplesOfNumbers;
?>

输出:

  

阵列

所以我尝试用array_push代替它,就像这样:

<?php
/* 
** Project Euler Problem 1
** If we list all the natural numbers below 10 that are multiples of 3 or 5,
** we get 3, 5, 6 and 9. The sum of these multiples is 23. 
** Find the sum of all the multiples of 3 or 5 below 1000.
*/
$numberOne = 3;
$numberTwo = 5;
$endingIndex = 1000;
$multiplesOfNumbers = array();  

for ($index = 1; $index <= $endingIndex; $index++) {
    if ($index % $numberOne == 0 && $index % $numberTwo == 0) {
        // $multipleOfNumbers[] = $index;
        array_push($multiplesOfNumbers, $index);
    }
}
echo $multiplesOfNumbers;
?>

输出相同。我错过了什么?

3 个答案:

答案 0 :(得分:6)

尝试这种方式:

print_r($multiplesOfNumbers);

答案 1 :(得分:2)

echo不会打印数组元素。使用print_r代替

答案 2 :(得分:0)

您必须遍历数组以获取数组的值(使用foreach)或使用类似var_dump()或print_r()的内容来回显数组。