- PHP Array Prepend
- array_unshift
- Parameters
- Return Values
- Changelog
- Examples
- See Also
- User Contributed Notes 12 notes
- PHP array_unshift
- Introduction to the PHP array_unshift() function
- PHP array_unshift() examples
- 1) Using PHP array_unshift() function to prepend one element to an array example
- 2) Using PHP array_unshift() function to prepend one element to an array example
- Prepending an element to the beginning of an associative array
- Summary
PHP Array Prepend
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 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.
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.
int array_unshift( $array, mixed $variable1 [, $variable2 [. ]])
var: The prepended variable
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.
$array = array ( «diwali» , «dushera» , «chirstmas» );
echo ( «The original array is:
» );
print_r( $array );array_unshift( $array , «ganesh puja» );
echo ( «
After prepending an element at the beginning:
» );
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 )
$array = array ( «a» => «apple» , «b» => «ball» , «c» => «cat» );
echo ( «The original array is:
» );
echo ( «After prepending an element at the beginning:
» );
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 )
If we print the array_unshift(), then output will be the number of new elements present in the array.
$array = array ( «a» => «apple» , «b» => «ball» , «c» => «cat» );
echo (array_unshift( $array , «Dog» ));
array_unshift
array_unshift() prepends passed elements to the front of the array . Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won’t be changed.
Note:
Resets array’s internal pointer to the first element.
Parameters
Return Values
Returns the new number of elements in the array .
Changelog
Version | Description |
---|---|
7.3.0 | This function can now be called with only one parameter. Formerly, at least two parameters have been required. |
Examples
Example #1 array_unshift() example
array_unshift ( $queue , «apple» , «raspberry» );
var_dump ( $queue );
?>
The above example will output:
array(4) < [0] =>string(5) "apple" [1] => string(9) "raspberry" [2] => string(6) "orange" [3] => string(6) "banana" >
Example #2 Usage with associative arrays
If one associative array is prepended to another associative array, the prepended array is numerically indexed into the former array.
$foods = [
‘apples’ => [
‘McIntosh’ => ‘red’ ,
‘Granny Smith’ => ‘green’ ,
],
‘oranges’ => [
‘Navel’ => ‘orange’ ,
‘Valencia’ => ‘orange’ ,
],
];
$vegetables = [
‘lettuce’ => [
‘Iceberg’ => ‘green’ ,
‘Butterhead’ => ‘green’ ,
],
‘carrots’ => [
‘Deep Purple Hybrid’ => ‘purple’ ,
‘Imperator’ => ‘orange’ ,
],
‘cucumber’ => [
‘Kirby’ => ‘green’ ,
‘Gherkin’ => ‘green’ ,
],
];
?php
array_unshift ( $foods , $vegetables );
var_dump ( $foods );
The above example will output:
array(3) < [0] =>array(3) < 'lettuce' =>array(2) < 'Iceberg' =>string(5) "green" 'Butterhead' => string(5) "green" > 'carrots' => array(2) < 'Deep Purple Hybrid' =>string(6) "purple" 'Imperator' => string(6) "orange" > 'cucumber' => array(2) < 'Kirby' =>string(5) "green" 'Gherkin' => string(5) "green" > > 'apples' => array(2) < 'McIntosh' =>string(3) "red" 'Granny Smith' => string(5) "green" > 'oranges' => array(2) < 'Navel' =>string(6) "orange" 'Valencia' => string(6) "orange" > >
See Also
- array_merge() — Merge one or more arrays
- array_shift() — Shift an element off the beginning of array
- array_push() — Push one or more elements onto the end of array
- array_pop() — Pop the element off the end of array
User Contributed Notes 12 notes
You can preserve keys and unshift an array with numerical indexes in a really simple way if you’ll do the following:
$someArray =array( 224 => ‘someword1’ , 228 => ‘someword2’ , 102 => ‘someword3’ , 544 => ‘someword3’ , 95 => ‘someword4’ );
$someArray =array( 100 => ‘Test Element 1 ‘ , 255 => ‘Test Element 2’ )+ $someArray ;
?>
now the array looks as follows:
array(
100=>’Test Element 1 ‘,
255=>’Test Element 2′
224=>’someword1′,
228=>’someword2′,
102=>’someword3′,
544=>’someword3′,
95=>’someword4′
);
array_merge() will also reindex (see array_merge() manual entry), but the ‘+’ operator won’t, so.
$arrayone =array( «newkey» => «newvalue» ) + $arrayone ;
?>
does the job.
Sahn’s example almost works but has a small error. Try it like this if you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:
Anonymous’ associative version wasn’t working for me, but it did with this small tweak:
Another way to tack something to the beginning of an array is with array_merge().
$plans = array(‘AARP’=>’Senior’, ‘AAA’=>’Automobile Club’);
$plans = array_merge(array(«BAR»=>»Best Available Rate»), $plans);
This becomes a nice little problem if you index your arrays out of order (while manually sorting). For example:
$recordMonths [ 3 ] = ‘8/%/2006’ ;
$recordMonths [ 4 ] = ‘7/%/2004’ ;
$recordMonths [ 0 ] = ‘3/%/2007’ ;
$recordMonths [ 1 ] = ‘2/%/2007’ ;
$recordMonths [ 5 ] = ’12/%/2000′ ;
$recordMonths [ 6 ] = ’11/%/2000′ ;
$recordMonths [ 7 ] = ’10/%/2000′ ;
$recordMonths [ 2 ] = ‘1/%/2007’ ;
for( $i = 0 ; $i < count ( $recordMonths ); $i ++)
<
$singleMonth = $recordMonths [ $i ];
echo «singleMonth: $singleMonth
» ;
>
array_unshift ( $recordMonths , ‘%’ );
for( $i = 0 ; $i < count ( $recordMonths ); $i ++)
<
$singleMonth = $recordMonths [ $i ];
echo «singleMonth: $singleMonth
» ;
>
?>
Produces:
singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 1/%/2007
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: %
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: 1/%/2007
It reindexes them based on the order they were created. It seems like if an array has all numeric indexes, then it should reindex them based on the order of their index. Just my opinion.
even simpler unshifting of a reference !
/**
* @return int
* @param $array array
* @param $value mixed
* @desc Prepend a reference to an element to the beginning of an array. Renumbers numeric keys, so $value is always inserted to $array[0]
*/
function array_unshift_ref (& $array , & $value )
$return = array_unshift ( $array , » );
$array [ 0 ] =& $value ;
return $return ;
>
?>
Actually this problem with the keys getting reindexed only happens when the keys are numerical:
$a = array( «f» => «five» , «s» => «six» , «t» =>
«twenty» );
print_r ( $a );
echo «\n» ;
foreach( $a as $key => $val )
echo «k: $key v: $val \n» ;
>
array_unshift ( $a , «zero» );
print_r ( $a );
echo «\n» ;
foreach( $a as $key => $val )
echo «k: $key v: $val \n» ;
>
?>
Array
(
[f] => five
[s] => six
[t] => twenty
)
k: f v: five
k: s v: six
k: t v: twenty
Array
(
[0] => zero
[f] => five
[s] => six
[t] => twenty
)
k: 0 v: zero
k: f v: five
k: s v: six
k: t v: twenty
If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:
If you need to change the name of a key without changing its position in the array this function may be useful.
function array_key_change ( $Old , $New , $In , $NewVal = NULL ) <
$Temp = array();
while(isset( $Temp [ $Old ]) == false ) <
list( $k , $v ) = each ( $In );
$Temp [ $k ] = $v ;
unset( $In [ $k ]);
>
if( $NewVal == NULL ) <
$NewVal = $Temp [ $Old ];
>
unset( $Temp [ $Old ]);
$Temp = array_reverse ( $Temp );
$In = array_merge (array( $New => $NewVal ), $In );
while(list( $k , $v ) = each ( $Temp )) <
$In = array_merge (array( $k => $v ), $In );
>
return( $In );
>
?>
I had a need tonight to convert a numeric array from 1-based to 0-based, and found that the following worked just fine due to the «side effect» of renumbering:
array_unshift ( $myArray , array_shift ( $myArray ));
?>
Last version of PHP deprecated unshifting of a reference.
You can use this function instead :
function array_unshift1 (& $ioArray , $iValueWrappedInAnArray ) <
$lNewArray = false ;
foreach ( array_keys ( $ioArray ) as $lKey )
$lNewArray [ $lKey + 1 ] = & $ioArray [ $lKey ];
$ioArray = array (& $iValueWrappedInAnArray [ 0 ]);
if ( $lNewArray )
foreach ( array_keys ( $lNewArray ) as $lKey )
$ioArray [] = & $lNewArray [ $lKey ];
return count ( $ioArray );
>
// before last PHP (now generates a deprecation warning)
array_unshift ( $a , & $v );
// since last PHP (caution, there is a wrapping array !!)
array_unshift1 ( $a , array (& $v ));
?>
- Array Functions
- array_change_key_case
- array_chunk
- array_column
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_is_list
- array_key_exists
- array_key_first
- array_key_last
- array_keys
- array_map
- array_merge_recursive
- array_merge
- array_multisort
- array_pad
- array_pop
- array_product
- array_push
- array_rand
- array_reduce
- array_replace_recursive
- array_replace
- array_reverse
- array_search
- array_shift
- array_slice
- array_splice
- array_sum
- array_udiff_assoc
- array_udiff_uassoc
- array_udiff
- array_uintersect_assoc
- array_uintersect_uassoc
- array_uintersect
- array_unique
- array_unshift
- array_values
- array_walk_recursive
- array_walk
- array
- arsort
- asort
- compact
- count
- current
- end
- extract
- in_array
- key_exists
- key
- krsort
- ksort
- list
- natcasesort
- natsort
- next
- pos
- prev
- range
- reset
- rsort
- shuffle
- sizeof
- sort
- uasort
- uksort
- usort
- each
PHP array_unshift
Summary: in this tutorial, you will learn how to use the PHP array_unshift() function to prepend one or more elements to the beginning of an array.
Introduction to the PHP array_unshift() function
To prepend one or more elements to an array, you use the array_unshift() function:
array_unshift ( array &$array , mixed . $values ) : int
Code language: PHP (php)The array_unshift() returns the new number of elements in the array.
Note that the array_unshift() function modifies the original array. The array_unshift() function prepends the elements to the input array as a whole. It preserves the prepended elements.
Since the array_unshift() function adds the new elements to the beginning of the input array, it changes the indexes to start from zero.
PHP array_unshift() examples
Let’s take some examples of using the PHP array_unshift() function.
1) Using PHP array_unshift() function to prepend one element to an array example
The following example uses the array_unshift() function to prepend an element to the beginning of an array:
$permissions = [ 'edit', 'delete', 'view' ]; array_unshift($permissions, 'new'); print_r($permissions);
Code language: HTML, XML (xml)Array ( [0] => new [1] => edit [2] => delete [3] => view )
Code language: plaintext (plaintext)- First, define an array with three elements.
- Second, prepend the ‘new’ element to the beginning of the array.
- Third, show the elements of the array using the print_r() function.
As you can see clearly from the output, the ‘new’ element gets the index zero while the existing indexes change accordingly.
2) Using PHP array_unshift() function to prepend one element to an array example
The following example uses the array_unshift() to prepend three elements to the beginning of an array:
$permissions = [ 'edit', 'delete', 'view' ]; array_unshift($permissions, 'new', 'approve', 'reject'); print_r($permissions);
Code language: HTML, XML (xml)Array ( [0] => new [1] => approve [2] => reject [3] => edit [4] => delete [5] => view )
Code language: plaintext (plaintext)Prepending an element to the beginning of an associative array
To prepend an element to an associative array, you use the + operator. For example:
$colors = [ 'red' => '#ff000', 'green' => '#00ff00', 'blue' => '#0000ff', ]; $colors = ['black' => '#000000'] + $colors; print_r($colors);
Code language: HTML, XML (xml)Array ( [black] => #000000 [red] => #ff000 [green] => #00ff00 [blue] => #0000ff )
Code language: PHP (php)Summary
- Use the PHP array_prepend() function to preprend one or more elements to the beginning of an array.