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?
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!
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.
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.
Use array_splice
as following:
array_splice($array, 3, 0, array('d'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With