Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert into array at a specified place

Tags:

php

array:

A-B-C-D-E-F 

J is the son of C. update array so:

A-B-C-J-D-E-F 

how do I insert J after C in the array?

I also map the array in a loop (array of comments for display). Will this method take a very long time to perform?

like image 970
Gal Avatar asked Nov 19 '09 15:11

Gal


People also ask

How do you push an element to an array at first position?

The unshift() method adds new elements to the beginning of an array.

Can we insert an element in middle of array in Java?

Hence in order to add an element in the array, one of the following methods can be done: By creating a new array: Create a new array of size n+1, where n is the size of the original array. Add the n elements of the original array in this array.

How do you insert an item at the beginning of an array in Java?

Java Array, by default, does not support to add or remove an element. Therefore, to add an element to the starting of given array, create a new array with the original size + 1, and then assign the new element to be added, and the elements in the original array to the new array.


2 Answers

You can use array_splice() with $length set to 0.

http://de.php.net/manual/en/function.array-splice.php

Example:

$arr_alphabet = array('a', 'b', 'd'); array_splice($arr_alphabet, 2, 0, 'c'); // $arr_alphabet is now: array('a', 'b', 'c', 'd'); 
like image 102
Pekka Avatar answered Sep 23 '22 09:09

Pekka


Use the splice function to solve this.

like image 37
Ben Fransen Avatar answered Sep 26 '22 09:09

Ben Fransen