0

I would like to insert two arrays after a particular index matches a condition in a multidimensional array while in a foreach loop and remove the existing array at that index

Sample array:

$array = array( 
  array( 1, 2, 3 ), 
  array( 4, 5, 6 ), 
  array( 7, 8, 9 ) 
);

After inserting and removing existing index array

$array = array( 
  array( 1, 2, 3 ), 
  array( 'new', 'array' ), 
  array( 'another', 'item' ), 
  array( 7, 8, 9 )
);

While in a loop when a condition is met so:

foreach ( $array as $index => $value ) :
    if ( $index % 2 == 0 ) :
    // insert two array elements in $array after index $index and remove $index
    endif;
endforeach;

Any help is appreciated.

UPDATE:

I've tried array_splice() but because it increases the length of the existing array on a match, it ends up doing overriding the new array elements in the loop as well.

1

2 Answers 2

2

Using a foreach loop for this would be wasteful. Just use array_splice() instead:

<?php
$array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
$replacement = [['new', 'array'], ['another', 'item']];
$target = 1;

array_splice($array, $target, 1, $replacement);
print_r($array);

Based on your edits you may want to try this:

<?php
$array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
$replacement = [['new', 'array'], ['another', 'item']];
$new = [];

foreach ($array as $k=>$v) {
    if ($k % 2 == 0) {
        foreach($replacement as $r) {
            $new[] = $r;
        }
    } else {
        $new[] = $v;
    }
}
print_r($new);
Sign up to request clarification or add additional context in comments.

5 Comments

The actual array has 100+ arrays and I'm only replacing indexes when a particular match is found. I tried to simplify the code for an answer without adding unnecessary complexity to the problem at hand.
You said "a particular index" so that's what I answered for. If you'd like to revise your question, please do so. It might also help to show what attempts you've made to solve the problem and where they went wrong.
I also said "while in a loop"
I apologize. array_splice() doesn't work. I'll make the original question more thorough.
You're going to have problems altering an array while you're iterating it, I do not advise it.
1

I got it work with the following changes:

$array = array( 
    array( 1, 2, 3 ), 
    array( 4, 5, 6 ), 
    array( 7, 8, 9 ) 
);

$new_array = array();

foreach ( $array as $index => $value ) {

    if ( $index % 2 == 0 ) {

        array_push( $new_array, array( 'new', 'array' ) );
        array_push( $new_array, array( 'another', 'array' ) );

        continue;

    }

    array_push( $new_array, $array[ $index ] );

}

$array = $new_array;

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.