'Divide/Split an array into two arrays one with even numbers and other with odd numbers
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 )
Solution 1:[1]
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);
?>
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alfa Riza |
| Solution 2 |
