Array Manipulation With PHP4 - Push And Pull
(Page 4 of 8 )
You can add an element to the end of an existing array with the array_push() function,
<?
// create array
$superheroes = array("spiderman", "superman", "captain marvel", "green
lantern");
array_push($superheroes, "the incredible hulk");
// $superheroes now contains ("spiderman", "superman", "captain marvel",
"green lantern", "the incredible hulk")
?>
and remove an element from the end with the
interestingly-named array_pop() function.
<?
// create array
$superheroes = array("spiderman", "superman", "captain marvel", "green
lantern");
array_pop($superheroes);
// $superheroes now contains ("spiderman", "superman", "captain marvel")
?>
If you need to pop an element off the top of the array, you
can use the array_shift() function,
<?
// create array
$superheroes = array("spiderman", "superman", "captain marvel", "green
lantern");
array_shift($superheroes);
// $superheroes now contains ("superman", "captain marvel", "green lantern")
?>
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:
<?
// create array
$students = array();
// returns an array containing 4 null values
$students = array_pad($students, 4, "");
?>
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");
?>
Next: Slice And Dice >>
More PHP Articles
More By Vikram Vaswani, (c) Melonfire