Pankaj Yogi
Pankaj Yogi

Reputation: 207

Merge two flat arrays in an alternating fashion to create a new flat array

I have two array like this::

$doctor = Array(
[0] => 4
[1] => 5
[2] => 8
[3] => 35
[4] => 41
[5] => 42
)

$clinic = Array(
[0] => 1
[1] => 3
[2] => 9
[3] => 15
[4] => 19
[5] => 20
)

Now i want to add these array like this

 $all = array(
 [0] => 4
 [1] => 1
 [2] => 5
 [3] => 3
 [4] => 8
 [5] => 9
 [6] => 35
 [7] => 15
 [8] => 41
 [9] => 19
 [10] => 42
 [11] => 20

I have tried this but it is not my expected output:

$all = array_merge( $doctor , $clinic );

Any solution?

Thanks

Upvotes: 0

Views: 40

Answers (1)

ashanrupasinghe
ashanrupasinghe

Reputation: 756

You can use for loop to do that

$all=[];
for($i=0;$i<6;$i++){
$all[]=$doctor[$i];
$all[]=$clinic[$i];
}

if you don't have same length for the arrays, Try

$doctor_size=sizeof($doctor);
$clinic_size=sizeof($clinic);
$all=[];
$size=$doctor_size;
if($doctor_size<$clinic_size){
$size=$clinic_size;
}
for($i=0;$i<$size;$i++){
if(isset($doctor[$i])){
$all[]=$doctor[$i];
}

if(isset($clinic[$i])){
$all[]=$clinic[$i];
}

}

Upvotes: 1

Related Questions