0

I want insert one array to another associative array at specific position, but for me the array_splice doesn't work. I want do this:

    $example = [
       'first' => 'element',
       'second' => 'element'];
    $example[] = [
       'third' => 'element',
       'fourth' => 'element'];

Now we have a associative array with inside with two another array. And I want to insert on another array in it, for example between it. It is important, i want to insert to a specific index.

     $insert[] = [
        'insert_first' => 'element',
        'insert_second' => 'element'];
     //I made before it: 
     $index = 1;
     array_splice($example, $index, 0, $insert); //but it doesn't work :(

I want the following result:

array(
 [0] => array(
    'first' => 'element',
    'second' => 'element'
 )
 [1] => array(
    'insert_first' => 'element',
    'insert_second' => 'element'
 )
 [2] => array(
    'third' => 'element',
    'fourth' => 'element'
 )
)

Can somebody help me how can i made it?

Thank, Balázs from Hungary.

3
  • 1
    I think you missed the [] in $example, it should be $example[] if you want the desired result Commented Mar 12, 2019 at 15:47
  • 1
    I don't think your starting array is what you think it is. Commented Mar 12, 2019 at 15:47
  • 1
    Look at php.net/manual/en/function.array-splice.php for assotiative array (string keys) array_splice_assoc Commented Mar 12, 2019 at 15:48

2 Answers 2

4
$example[] = [
   'first' => 'element',
   'second' => 'element'];
$example[] = [
   'third' => 'element',
   'fourth' => 'element'];
$insert[] = [
    'insert_first' => 'element',
    'insert_second' => 'element'];

$index = 1;
array_splice($example, $index, 0, $insert);
print_r($example);

Gives you :

Array ( 
 [0] => Array ( [first] => element [second] => element ) 
 [1] => Array ( [insert_first] => element [insert_second] => element ) 
 [2] => Array ( [third] => element [fourth] => element ) )
Sign up to request clarification or add additional context in comments.

Comments

3

Your original array is incorrect. Correct one:

// Here you have array with one element which is array:
$example = [
   [
       'first' => 'element',
       'second' => 'element'
   ]
];
// Add another element which is array too
$example[] = [
   'third' => 'element',
   'fourth' => 'element'];
// define insert array
$insert[] = [
    'insert_first' => 'element',
    'insert_second' => 'element'
];
$index = 1;
array_splice($example, $index, 0, $insert);

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.