Home Tutorial Php Phpbasics PHP Array Prepend

 
 

PHP Array Prepend
Posted on: October 19, 2009 at 12:00 AM
PHP Array Prepend: In this tutorial you will come to know about how to prepend or add elements at the beginning of an array, in addition this tutorial has many examples of PHP array prepend technique.

PHP Array Prepend

In this PHP Array tutorial we will come to know about how to add elements at the beginning of an array. To add elements at the beginning we will use array_unshift() function.

General Format

 int array_unshift( $array, mixed $variable1 [, $variable2 [,...]])

Parameters

array: Input array

var: The prepended variable

Return Value

Returns the new number of elements in the array

array_ unshift() prepends or adds the elements at the beginning of an array, the list of elements add at the beginning as a whole. The index position or the numeric key values will be modified to  zero.

Example 1:

<?php

$array=array("diwali","dushera","chirstmas");

echo("<b>The original array is:</b><br/>");

print_r($array);array_unshift($array,"ganesh puja");

echo("<br/><b>After prepending an element at the beginning:</b><br/>");

print_r($array);

?>

Output:

The original array is:
Array ( [0] => diwali [1] => dushera [2] => chirstmas )
After prepending an element at the beginning:
Array ( [0] => ganesh puja [1] => diwali [2] => dushera [3] => chirstmas )

Example 2:

<?php

$array=array("a"=>"apple","b"=>"ball","c"=>"cat");

echo("<b>The original array is:</b><br/>");

print_r($array);

array_unshift($array,"dog");

echo("<b>After prepending an element at the beginning:</b><br/>");

print_r($array);

?>

Output:

The original array is:
Array ( [a] => apple [b] => ball [c] => cat )
After prepending an element at the beginning:
Array ( [0] => dog [a] => apple [b] => ball [c] => cat )

Example 3:

If we print the array_unshift(), then output will be the number of new elements present in the array.

<?php

$array=array("a"=>"apple","b"=>"ball","c"=>"cat");

echo (array_unshift($array,"Dog"));

?>

Output:

4

Example 4:

<?php

$a=array(0=>"Delhi",1=>"West Bengal");

array_unshift($a,"Bihar");

print_r($a);

?>

Output:

Array ( [0] => Bihar [1] => Delhi [2] => West Bengal )

Related Tags for PHP Array Prepend:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.