Jump to: navigation, search

Php array unshift

From w3cyberlearnings

Contents

PHP function array_unshift

This function adds an element to the beginning of an array.

Syntax array_unshift

  • array: array input
  • element: element to add to the array
array_unshift(array, $element);

Note

  • array_pop() function - remove the last element in an array
  • array_push() function - add the element at the end of the array
  • array_shift() function - add element at the beginning of an array

Example 1

<?php

$course = array('English', 'Computer', 'Maths', 'Sport');
array_unshift($course, 'Programming');

print_r($course);
?>

Output

Array
(
    [0] => Programming
    [1] => English
    [2] => Computer
    [3] => Maths
    [4] => Sport
)

Example 2: Use array_merge

<?php
<?php

$course1 = array('Programming');
$course2 = array('English', 'Computer', 'Maths', 'Sport');

$course = array_merge($course1, $course2);

print_r($course);
?>

Output


Array
(
    [0] => Programming
    [1] => English
    [2] => Computer
    [3] => Maths
    [4] => Sport
)

Related Links


Navigation
Web
SQL
MISC
References