简体   繁体   中英

Outputting odd and even number in array

Using below array, i'm trying to use foreach loop to iterate through each item. Then i need to apply if condition to check if the given number is even and odd. I also need to create two arrays one for even and one for odd and push each number in their respective category.

So i have done this so far:

These are the two arrays i created to push through the values to.

}

$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];

$array_odd = [];

$array_even = [];
 foreach ($numbers as $value)
{
 if (value %2 == 0)

 {
   $array_even = $value;
   echo $array_even;
}
else 
{    
$array_odd = $value;  
  echo $array_odd;
}

I'd like to know if i'm using the correct solution or are there major errors im committing?

It will surely work like charms.

$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];

$array_odd = [];

$array_even = [];
 foreach ($numbers as $value)
 {
  if ($value %2 == 0)
  {
    $array_even[] = $value;
  }
  else 
  {    
   $array_odd[] = $value;
  }
 }
 echo "<pre>";
 print_r($array_odd);
 echo "<pre>";
 print_r($array_even);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM