Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an array value to the middle of an array?

Tags:

Lets say I have this array:

$array = array(1,2,'b','c',5,6,7,8,9.10); 

Later in the script, I want to add the value 'd' before 'c'. How can I do this?

like image 374
Citizen Avatar asked Jan 27 '10 18:01

Citizen


People also ask

How do you add an array to an array?

To append one array to another, use the push() method on the first array, passing it the values of the second array. The push method is used to add one or more elements to the end of an array. The method changes the contents of the original array. Copied!

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 add a value to an array in Python?

If you are using List as an array, you can use its append(), insert(), and extend() functions. You can read more about it at Python add to List. If you are using array module, you can use the concatenation using the + operator, append(), insert(), and extend() functions to add elements to the array.


1 Answers

Use array_splice as following:

array_splice($array, 3, 0, array('d')); 
like image 125
Ivan Nevostruev Avatar answered Oct 08 '22 09:10

Ivan Nevostruev