It’s simple, the check is comparing to the array and not with the element of array, as it should. That is, it always turns out false because a array, as a whole is always different from 0. Missing brackets with the index to catch 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 />";
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Since you are learning, I suggest using a control that will avoid the mistake made:
$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 />";
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
The foreach
sweeps all over the array. Almost always this is what you want. It controls it best for you. It is always recommended to use it when possible.
Can simplify 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>";
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
In some circumstances you can use the function each()
.
Thanks friend, it worked out here! Thanks for the explanation.
– André