Even or odd of an array in PHP

7

I need to create an array and tell if the values inside it are even or odd. I made the code this way:

<?php
$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 % 2 == 0)
        echo "O Número é par: $par_ou_impar[$i]<br />";
    else
        echo "O Número é impar: $par_ou_impar[$i]<br />";
 }
?>

It shows me all the values that are inside the array on the screen, but the result all came out as odd.

    
asked by anonymous 31.01.2016 / 18:18

4 answers

7

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.

    
31.01.2016 / 18:22
5

Missed you a detail, use [$i] here:

if ($par_ou_impar % 2 == 0)
                ^

to be compared to the element being iterated. So the right code will be:

$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 />";
}

example: link

    
31.01.2016 / 18:21
3

I leave my contribution with array_map

function checarNumeros($numeros){
   return ($numeros % 2 ) ? TRUE : FALSE;
}


$parOuImpar  = array(2,3,4,56,5,42,98,100);


$array  = array_map("checarNumeros", $parOuImpar);

print_r($array);

An array is returned, whereas the odd returns 1 and the pairs return 0.

    
01.02.2016 / 14:14
2

I know it has already been solved, but I leave here an alternative:

<?php
   $par_ou_impar = array(2,3,4,56,5,42,98,100);
   for ($i = 0; $i < count($par_ou_impar); $i++){
       echo ($par_ou_impar[$i] % 2) ? "{$par_ou_impar[$i]} é impar\n" : "{$par_ou_impar[$i]} é par\n";
   }
?>
    
31.01.2016 / 19:12