Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to splice an array to insert array at specific position?

$custom = Array(
            Array(
                'name'  =>  $name1,
                'url'   =>  $url1
            ),
            Array(
                'name'  =>  $name_a,
                'url'   =>  $url_a
            )
        );

I am attempting to splice the array with the following:

$bread_elem = array('name' => 'Golf', 'url' => $slug . $parent_slug);
array_splice($custom, 1, 0, $bread_elem);

I want my array to become the following, with the value of $sale_bread_elem inserted into position one within the array. I can't see what I am doing wrong.

$custom = Array(
            Array(
                'name'  =>  $name1,
                'url'   =>  $url1
            ),
            Array(
                'name'  =>  'Golf',
                'url'   =>  $slug . $parent_slug
            ),
            Array(
                'name'  =>  $name_a,
                'url'   =>  $url_a
            )
        );
like image 927
crmpicco Avatar asked Jun 11 '12 09:06

crmpicco


People also ask

What is the difference between splice () and position of an array?

The position specifies the position of the first item to delete and the num argument determines the number of elements to delete. The splice () method changes the original array and returns an array that contains the deleted elements. Let’s take a look at the following example.

How to insert elements using JavaScript array splice?

Inserting elements using JavaScript array splice. You can insert one or more element into an array by passing three or more arguments to the splice() method with the second argument is zero.

How to insert an element at a specific position in array?

How to Insert an element at a specific position in an Array in Java First get the element to be inserted, say x Then get the position at which this element is to be inserted, say pos Create a new array with the size one greater than the previous size Copy all the elements from previous array into ...

How to delete elements in an array using Python splice?

To delete elements in an array, you pass two arguments into the splice () method as follows: The position specifies the position of the first item to delete and the num argument determines the number of elements to delete.


1 Answers

array_splice­Docs takes an array of elements to insert. So the call should actually be

array_splice($custom, 1, 0, array($bread_elem));
like image 155
NikiC Avatar answered Sep 27 '22 18:09

NikiC