Anish Ansari
Anish Ansari

Reputation: 179

How to insert values in the beginning in the array using loop

I want to display even and odd number both in the same array using loop. how can I do that in PHP ? I want to insert even number first and odd later.

I was trying to store even $i index of the array and odd in $j of the array but how can I now add first even then odd.

Output should be in single array

 2,4,6,8,1,3,5,7,9 

Upvotes: 0

Views: 58

Answers (2)

Zain Farooq
Zain Farooq

Reputation: 2964

First run loop for even number and store it in the array and in the same way run the loop for odd numbers

$array = array();
for($i = 1; $i < 9; $i++)
{
 if($i%2 == 0)
 {
   $array[] = $i;
 }
}

for($i = 1; $i < 9; $i++)
{
 if($i%2 == 1)
 {
   $array[] = $i;
 }
}
print_r($array);

Here is the demo

Upvotes: 2

Accountant م
Accountant م

Reputation: 7483

Another algorithm looping 1 time depends also on the Modulo operator

<?php

$array = [1,2,3,4,5,6,7,8,9];

$odd = [];
$even = [];

foreach($array as $num){
    if ($num % 2){
        $odd[] = $num;
    } else {
        $even[] = $num;
    }
}
$finalArray = array_merge($even, $odd);

var_dump($finalArray);

This outputs

array(9) {
  [0]=>
  int(2)
  [1]=>
  int(4)
  [2]=>
  int(6)
  [3]=>
  int(8)
  [4]=>
  int(1)
  [5]=>
  int(3)
  [6]=>
  int(5)
  [7]=>
  int(7)
  [8]=>
  int(9)
}

Live demo https://3v4l.org/k7CmG

Upvotes: 2

Related Questions