Monday, 13 August 2018

How to Add Element(s) to the Beginning of an Array in PHP?

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.
1
2
3
<?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 –
1
2
3
4
5
6
7
<pre>
<?php
$even_nos = array(4, 6, 8, 10, 12, 14, 16);
array_unshift($even_nos, 2);
print_r($even_nos);
?>
</pre>

Output:
How it works:
Line 3The array $even_nos contains some even numbers. We’ll add 2 in the first index of this array.
Line 4array_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 5Here 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-
1
2
3
4
5
6
7
<pre>
<?php
$numbers = array(4, 5, 6, 7, 8, 9, 10);
array_unshift($numbers, 1, 2, 3);
print_r($numbers);
?>
</pre>

Output:

 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-
    1
    2
    3
    4
    5
    6
    7
    <pre>
    <?php
    $numbers = array("first"=>4, "second"=>5, "third"=>6);
    array_unshift($numbers, 1, 2, 3);
    print_r($numbers);
    ?>
    </pre>

    Output:

0 comments:

Post a Comment