1

I'm trying to create a new array containing values from pre-existing arrays.

<?php

$array1 = array(
    0 => 101,
    1 => 102,
    2 => 121,
    3 => 231,
    4 => 232,
    5 => 233
);

$array2 = array(
    0 => 58,
    1 => 98,
    2 => 45,
    3 => 48,
    4 => 45,
    5 => 85
);

$result = array();

Notice that the first element is from $array1, second element from $array2 and so on.

Any pointer is highly appreciated.

2 Answers 2

1

Example of how you can achieve this:

    $array = array(4,5,6);
    $array2 = array(8,9,0,12,44,);
    $count1 = count($array);
    $count2 = count($array2);
    $count = ($count1 > $count2) ? $count1 : $count2;
    $rez = array();
    for ($i = 0; $i < $count; $i++) {
        if ($i < $count1) {
           $rez[] = $array[$i];
        } 
        if ($i < $count2) {
           $rez[] = $array2[$i];
        }


    }

var_dump($rez);

Result will be an array

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

but if you need to save empty values you can remove this checks if ($i < $count2)

Sign up to request clarification or add additional context in comments.

Comments

1

You can try with for or foreach loops (in case $array1 and $array2 have the same number of elements with the same indexes):

$result = array();

for($i = 0; $i < count($array1); $i++){
  $result[] = $array1[$i];
  $result[] = $array2[$i];
}

[] gives you a feature to not specify the index, so you can just push them one by one from each array to the result array.

Example with for loop

Example with foreach loop

There is also a more straightforward way to do it, without worrying about lost indexes and elements :

$i = 0;

foreach($array1 as $v){
  $result[$i] = $v;
  $i = $i+2;
}

$i = 1;

foreach($array2 as $v){
  $result[$i] = $v;
  $i = $i+2;
}

ksort($result);

Example

It looks a bit cumbersome, so you can write a function to make it more elegant :

function build_array(&$array, $input, $counter){
   foreach($input as $v){
      $array[$counter] = $v;
      $counter = $counter+2;
   }
}

build_array($result, $array1, 0);
build_array($result, $array2, 1);
ksort($result);

Example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.