您的代码找不到偶数。您正在确定它们在数组中的位置,并仅打印这些索引的值。看看这个 php 片段。
<?php
$myarray = array(1,2,3,4,5,6,7,8,9,10);
// Array indexes start at 0, not 1.
for ($i = 0; $i < count($myarray); $i++) {
echo "Index ", $i, ", value ", $myarray[$i], ": ";
// A value is even if there's no remainder when you divide it by 2.
if ($myarray[$i] % 2 == 0) {
echo "even\n";
}
else {
echo "odd\n";
}
}
?>
把它放在一个文件中,然后通过 php.ini 运行它。你应该看到这个。
Index 0, value 1: odd
Index 1, value 2: even
Index 2, value 3: odd
Index 3, value 4: even
Index 4, value 5: odd
Index 5, value 6: even
Index 6, value 7: odd
Index 7, value 8: even
Index 8, value 9: odd
Index 9, value 10: even
这个较短的版本将只打印偶数值。
<?php
$myarray = array(1,2,3,4,5,6,7,8,9,10);
for ($i=0; $i < count($myarray); $i++) {
if ($myarray[$i] % 2 == 0) {
echo "Index ", $i, ", value ", $myarray[$i], "\n";
}
}
?>
Index 1, value 2
Index 3, value 4
Index 5, value 6
Index 7, value 8
Index 9, value 10