It's simple, in the check it's comparing to the array and not to the array element, as it should. That is, it always fakes because a array as a whole is always different from the value 0. It failed the index brackets to get the element:
$par_ou_impar = array(2,3,4,56,5,42,98,100);
for ($i = 0; $i < count($par_ou_impar); $i++){
if ($par_ou_impar[$i] % 2 == 0)
echo "O Número é par: $par_ou_impar[$i]<br />";
else
echo "O Número é impar: $par_ou_impar[$i]<br />";
}
See running on ideone .
Since you are learning, I suggest you use a control that will prevent the error committed:
$par_ou_impar = array(2, 3, 4, 56, 5, 42, 98, 100);
foreach ($par_ou_impar as $item) {
if ($item % 2 == 0)
echo "O Número é par: $item<br />";
else
echo "O Número é impar: $item<br />";
}
See working on ideone .
foreach
scans the entire array . This is almost always what you want. It better controls this for you. It is always recommended to use it when possible.
You can simplify it even more:
$par_ou_impar = array(2, 3, 4, 56, 5, 42, 98, 100);
foreach ($par_ou_impar as $item) {
echo "O Número é " . ($item % 2 == 0 ? "par: " : "impar: ") . $item . "<br>";
}
See running on ideone .
In some circumstances you can use the each()
function.