This may come as a bit of a shock to you, but PHP's arrayfunctions can do a lot more than just count the elements of an array oriterate through key-value pairs. This article takes an in-depth look atPHP's less well-known array manipulation tools, illustrating how they canbe used to write tighter, more efficient code...and have some fun in thebargain as well!
while the array_unshift() function takes care of adding
elements to the beginning of the array.
<?
// create array
$superheroes = array("spiderman", "superman", "captain marvel", "green
lantern");
array_unshift($superheroes, "the human torch");
// $superheroes now contains ("the human torch", "spiderman", "superman",
"captain marvel", "green lantern")
?>
In case you need an array of a specific length, you can use
the array_pad() function to create an array and pad it with empty elements (or elements containing a user-defined value). The following example should make this clearer:
The second argument also specifies the direction of padding,
while the third argument to the function specifies the value to be used for the empty elements.
<?
// create array
$desserts = array("chocolate mousse", "tiramisu", "apple pie", "chocolate
fudge cake", "apricot fritters");
// returns an array containing 8 elements
// ("chocolate mousse", "tiramisu", "apple pie", "chocolate fudge cake",
"apricot fritters", "dummy", "dummy", "dummy")
// array is padded to the right since the size is positive
$desserts = array_pad($desserts, 8, "dummy");
// this would return the same array, but padded to the left (note the
negative size)
// ("dummy", "dummy", "dummy", "chocolate mousse", "tiramisu", "apple pie",
"chocolate fudge cake", "apricot fritters")
$desserts = array_pad($desserts, -8, "dummy");
?>