1

I have 2 arrays :

$arr1 = array('1', '2', '3', '4', '5', '6', '7');
$arr2 = array('a', 'b', 'c', 'd', 'e');

I want to loop $arr2 into $arr1 but if the length of $arr1 is less than the algorithm requires, only use as many elements of $arr2 as necessary.

I want to achieve this result:

$arr2 = array('1', '2', '3', 'a', '4', '5', '6', 'b', '7');

I have already tried :

$count = ceil(count($arr1) / 3) - 1;
for ($i = 0; $i < $count; $i++) {
    array_splice($arr1, 3, 0, $arr2);
}

3 Answers 3

3

You are on the right track, but you need make the splice point ($i+1)*3, and only splice in the $arr2[$i] value, not the entire array. Also you need to work backwards from the end as inserting values into the array causes the indexes to change.

$arr1 = array('1', '2', '3', '4', '5', '6', '7');
$arr2 = array('a', 'b', 'c', 'd', 'e');
$count = ceil(count($arr1) / 3) - 1;
for ($i = $count - 1; $i >= 0; $i--) {
    array_splice($arr1, ($i + 1) * 3, 0, $arr2[$i]);
}
print_r($arr1);

Output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => a
    [4] => 4
    [5] => 5
    [6] => 6
    [7] => b
    [8] => 7
)

Demo on 3v4l.org

Note that dependent on the result you want to achieve when $arr1 is a multiple of 3 elements, you may want to change

$count = ceil(count($arr1) / 3) - 1;

to

$count = ceil((count($arr1) + 1) / 3) - 1;
Sign up to request clarification or add additional context in comments.

Comments

1

You can just insert element of $arr2 ervey 3 element2 of $arr1, Demo

$result = [];
foreach($arr1 as $key => $value){
    $result[] = $value;
    if((0 == ($key + 1) % 3) && isset($arr2[($key + 1)/3-1])){
        $result[] = $arr2[($key + 1)/3-1];
    }
}
print_r($result);

1 Comment

It prints a twice. You probably mean $result[] = $arr2[intval(($key + 1) / 3) - 1];
0

At every third index, splice in a member of your other array. Note the original array changes in size, so we need to adjust inserted key accordingly upon each splice.

<?php
for($i=3, $s=0, $c=count($arr1); $i<$c; $i+=3, $s++) {
    array_splice($arr1, $i+$s, 0, $arr2[$s]);
}
var_export($arr1);

Output:

array (
  0 => '1',
  1 => '2',
  2 => '3',
  3 => 'a',
  4 => '4',
  5 => '5',
  6 => '6',
  7 => 'b',
  8 => '7',
)

Same omitting the statement of the loop

for(
    $i=3, $s=0, $c=count($arr1);
    $i<$c;
    array_splice($arr1, $i+$s, 0, $arr2[$s++]), $i+=3
);

1 Comment

Start at index 3, to bypass the if.

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.