Even numbers in an array with for - PHP

Asked

Viewed 280 times

0

Hello, I would like to understand where my code is wrong. I need to filter only the even numbers of the array using for. But it returns the following answer to me - "The filter is not working very well".

function filtraArray($umArray) {
    $resultado = [];

    for($i = 0; $i > count($umArray); $i++){
      if ($umArray[$i] % 2 == 0) {
        echo $resultado = $umArray[$i];
      }
    }

    return $resultado;
}

Thank you :)

  • 1

    On the line echo $resultado = $umArray[$i]; you are replacing the value of the variable $resultado every time a value is even. The correct one would be $resultado[] = $umArray[$i];. This way, every time a number is even, an index will be created in the variable $resultado.

  • Thank you very much!!!

1 answer

0


I found two flaws in your code:

1) You wrote that for should be repeated while i for greater than the number of items in the array, while actually it should be repeated while i for minor than the number of items in the array.

2) The variable $resultado is an array, and since you want the even numbers inside it, you must include the new values and not replace them. Then the inclusion will be done as follows: $resultado[] = $umArray[$i];

Below the corrected code, I hope to have helped!

function filtraArray($umArray) {  
    $resultado = [];

    for($i = 0; $i < count($umArray); $i++){
      if ($umArray[$i] % 2  == 0) {
        $resultado[] = $umArray[$i];
      }
    }

    return $resultado;
}

$array = [1,2,3,4,5,6,7,8,9,12,13,14,15,15,654,565678,87978977];
$resultado = filtraArray($array);
print_r($resultado);
  • Thank you so much, it worked, I didn’t even notice!

  • For nothing, in case you have helped, remember to click +1 and mark my answer as chosen!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.