PHPRO.ORG

This function became deprecated with the introduction of the built in function array_unshift(). The old implementation is left for historical purposes.

This simple function is an opposite of array_push() which pushes an element onto the end of an array. But if we wish to push the element on the beginning of an array, we are left to fend for ourselves. This function only works for numerically index arrays.


<?php
/*
* As simple array
*/
$array = array('kangaroo''platypus''wombat');
/*
* First we see how it looks before we alter the array
*/
foreach($array as $key=>$value)
{
        echo 
$key .' -- '.$value.'<br />';
}

/*
* The element we want at the beginning of the array
*/
$element 'dingo';

/*
* Now we see how it looks after
*/
foreach(array_start_push($array$element) as $key=>$value)
{
    echo 
$key .' -- '.$value.'<br />';
}

/**
*
* Function array_start_push
*
* Push an element onto the beginning of an array
*
* @var array $array
*
* @var string $element
*
* @return array
*
*/
function array_start_push($array$element){
 return 
array_merge(array($element), $array);
}
?>

The first foreach iteration will produce this:

0 -- kangaroo
1 -- platypus
2 -- wombat

The second iteration of foreach with the new added array element should produce this:

0 -- dingo
1 -- kangaroo
2 -- platypus
3 -- wombat