Voting

: three plus three?
(Example: nine)

The Note You're Voting On

weikard at gmx dot de
19 years ago
You cannot insert with array_splice an array with your own key. array_splice will always insert it with the key "0".

<?php
// [DATA]
$test_array = array (
row1 => array (col1 => 'foobar!', col2 => 'foobar!'),
row2 => array (col1 => 'foobar!', col2 => 'foobar!'),
row3 => array (col1 => 'foobar!', col2 => 'foobar!')
);

// [ACTION]
array_splice ($test_array, 2, 0, array ('rowX' => array ('colX' => 'foobar2')));
echo
'<pre>'; print_r ($test_array); echo '</pre>';
?>

[RESULT]

Array (
[row1] => Array (
[col1] => foobar!
[col2] => foobar!
)

[row2] => Array (
[col1] => foobar!
[col2] => foobar!
)

[0] => Array (
[colX] => foobar2
)

[row3] => Array (
[col1] => foobar!
[col2] => foobar!
)
)

But you can use the following function:

function array_insert (&$array, $position, $insert_array) {
$first_array = array_splice ($array, 0, $position);
$array = array_merge ($first_array, $insert_array, $array);
}

<?php
// [ACTION]

array_insert ($test_array, 2, array ('rowX' => array ('colX' => 'foobar2')));
echo
'<pre>'; print_r ($test_array); echo '</pre>';
?>

[RESULT]

Array (
[row1] => Array (
[col1] => foobar!
[col2] => foobar!
)

[row2] => Array (
[col1] => foobar!
[col2] => foobar!
)

[rowX] => Array (
[colX] => foobar2
)

[row3] => Array (
[col1] => foobar!
[col2] => foobar!
)
)

[NOTE]

The position "0" will insert the array in the first position (like array_shift). If you try a position higher than the langth of the array, you add it to the array like the function array_push.

<< Back to user notes page

To Top