Problem:
You have an array(ex. the following one) which has all even numbers as values. Now, you want to a new item(suppose 2) in the first position of the array.
<?php $even_nos = array(4, 6, 8, 10, 12, 14, 16); ?>
Solution:
You can use array_unshift() function to prepend 2 in the beginning of the above array. Let’s see how in the following example –
<pre> <?php $even_nos = array(4, 6, 8, 10, 12, 14, 16); array_unshift($even_nos, 2); print_r($even_nos); ?> </pre>
[wpdm_file id=65]
Output:
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 [5] => 12 [6] => 14 [7] => 16 )
How it works:
Line 3 | The array $even_nos contains some even numbers. We’ll add 2 in the first index of this array. |
Line 4 | array_shift() function takes the $even_nos array in its first parameter and the 2 as its second parameter which we want to add in the first index of the $even_no array. The function adds 2 in the array and returns it. |
Line 5 | Here we print the array. |
array_unshift() also allows to prepend multiple items at a time
The following example prepends 1, 2, and 3 in the beginning of the $number array-
<pre> <?php $numbers = array(4, 5, 6, 7, 8, 9, 10); array_unshift($numbers, 1, 2, 3); print_r($numbers); ?> </pre>
[wpdm_file id=66]
Output:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 )
Things to remember about array_unshift() array
- In the order you write multiple items those are to be added inside the array_unshift() array, the order those elements will be prepended in the array. See the second example above·
- If the supplied array is an indexed array, after prepending new element(s) the keys of the supplied array are modified and serialized from 0. See examples above example.
- If the supplied array is an associative array, after prepending new item(s) the keys of the associative array will not be changed. See the example below-
<pre> <?php $numbers = array("first"=>4, "second"=>5, "third"=>6); array_unshift($numbers, 1, 2, 3); print_r($numbers); ?> </pre>
Output:Array ( [0] => 1 [1] => 2 [2] => 3 [first] => 4 [second] => 5 [third] => 6 )
[wpdm_file id=67]