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!
A number of other functions are available to help you perform miscellaneous array manipulation. For example, the array_flip() function can be used to interchange keys and values in an array,
while the array_merge() function combines multiple arrays
into one single array.
<?
// create arrays
$good_guys = array("princess" => "Leia", "teacher" => "Yoda", "new hope" =>
"Luke");
$bad_guys = array("bad guy" => "Darth", "worse guy" => "The Emperor");
// returns a combined array("princess => Leia", "teacher => Yoda", "new
hope => Luke", "bad guy => Darth", "worse guy => The Emperor")
$starwars = array_merge($good_guys, $bad_guys);
?>
The array_diff() function accepts two or more arrays as
arguments, and returns an array containing all those values of the first array which are absent in the remaining ones,
while the array_intersect() function does the opposite,
calculating a list of those values of the first array which are present in all the remaining ones.
The array_rand() function randomly returns one or more keys
from an array.
<?
// create array
$desserts = array("chocolate mousse", "tiramisu", "apple pie", "chocolate
fudge cake", "apricot fritters");
// returns the random array (1, 3)
array_rand($desserts, 2);
// create array
$starwars = array("princess" => "Leia", "teacher" => "Yoda", "new hope" =>
"Luke", "bad guy" => "Darth", "worse guy" => "The Emperor");
// returns the random array ("princess", "bad guy")
array_rand($starwars, 2);
?>
And finally, the very useful array_walk() function allows you
to run a user-defined function on every element of an array. The following example uses it to apply a specific number format to all the numbers in an array:
<?
// create arrays
$numbers = array(1, 567, 1.6777777777777, 0.031, 100.1, -98.6);
$new_numbers = array();
// function to format numbers and add them to new array
function format($num)
{
global $new_numbers;
$new_numbers[] = sprintf("%1.2f", $num);
}
// runs the function format() on every element of $numbers
array_walk($numbers, "format");
// $new_numbers now contains ("1.00", "567.00", "1.68", "0.03", "100.10",
"-98.60")
?>
And that's about all I have. I hope you enjoyed this article,
and that it offered you some insight into the massive amount of power at your disposal when it comes to manipulating arrays. Should you require more information, the best place to go is the PHP manual page on arrays at http://www.php.net/manual/en/ref.array.php
Take care, and I'll see you soon!
Note: All examples in this article have been tested on Linux/i586 with PHP 4.0.6. Examples are illustrative only, and are not meant for a production environment. YMMV!