Home > Mobile >  Divide an array into two arrays one with even numbers and other with odd numbers
Divide an array into two arrays one with even numbers and other with odd numbers

Time:04-06

Please see my script, and identify the issue. Trying to Split an array into two arrays by value even or odd without built-in functions in PHP

<?php
$array = array(1,2,3,4,5,6);
$length = count($array);
$even = array();
for($i=0; $i < $length; $i  ){
  if($array[$i]/2 == 0){
     $even[] = $array[$i];
  }
  else{
     $odd[] = $array[$i];
  }
}
print_r($even);
echo "<br/>";
print_r($odd);
?>

current output
Array ( )
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )

CodePudding user response:

Try the modulo % operator when you check for even numbers. It gets the remainder when you divide your value by 2.

if($array[$i] % 2 == 0)

Your current code divides your value by 2 then gets the quotient, that's why it doesn't equate to 0. 2/2 = 1 4/2 = 2 and so on...

Hope this helps.

CodePudding user response:

your error is in if, you want to check if the number is odd or even, you have to use modulus %. So your code becomes like this

<?PHP $array = array(1,2,3,4,5,6);
$length = count($array);
$even = array();
for($i=0; $i < $length; $i  ){
  if($array[$i]%2 == 0){
$even[] = $array[$i];
}
else{
  $odd[] = $array[$i];
}
}
print_r($even);
echo "<br/>";
print_r($odd);
?>
  •  Tags:  
  • php
  • Related