Array Manipulation With PHP4 - When Size Does Matter... (
Page 3 of 8 )
Once an array
has been created, it's time to use it. Within the context of an array, the most
important (and commonly-used) function is the sizeof() function, which returns
the size of (read: number of elements within) the array.
Here's an
example:
<?
// create array
$desserts = array("chocolate mousse", "tiramisu", "apple pie", "chocolate
fudge cake", "apricot fritters");
// returns 5
echo sizeof($desserts);
// create array
$movies = array("romance" => "Moulin Rouge", "epic" => "Gladiator",
"action" => "Rambo", "horror" => "The Sixth Sense");
// returns 4
echo sizeof($movies);
?>
If you're using a hash, the array_keys() and array_values()
functions come in handy to get a list of all the keys and values within the
array.
<?
// create array
$starwars = array("princess" => "Leia", "teacher" => "Yoda", "new hope" =>
"Luke", "bad guy" => "Darth", "worse guy" => "The Emperor");
// returns the array ("princess", "teacher", "new hope", "bad guy", "worse
guy")
array_keys($starwars);
// returns the array ("Leia", "Yoda", "Luke", "Darth", "The Emperor")
array_values($starwars);
?>
And the in_array() function can tell you whether or not a
particular value exists in an array.
<?
// create array
$starwars = array("princess" => "Leia", "teacher" => "Yoda", "new hope" =>
"Luke", "bad guy" => "Darth", "worse guy" => "The Emperor");
// returns true
echo in_array("Yoda", $starwars);
// returns false
echo in_array("Obi-Wan", $starwars);
?>
An alternative (and sometimes more efficient) approach to the
one above would be to scan the array for a value match and return the
corresponding key. If this is what you need, consider the array_search()
function, which is designed just for this purpose:
<?
// create array
$starwars = array("princess" => "Leia", "teacher" => "Yoda", "new hope" =>
"Luke", "bad guy" => "Darth", "worse guy" => "The Emperor");
// returns "bad guy"
echo array_search("Darth", $starwars);
?>
You can convert array elements into regular PHP variables
with the list() and extract() functions. The list() function assigns array
elements to variables,
<?
// create array
$desserts = array("chocolate mousse", "tiramisu", "apple pie", "chocolate
fudge cake", "apricot fritters");
// assign elements to variables
list($a, $b, $c, $d, $e) = $desserts;
// returns "tiramisu"
echo $b;
?>
while the extract() function iterates through a hash,
converting the key-value pairs into corresponding variable-value pairs.
<?
// create array
$starwars = array("princess" => "Leia", "teacher" => "Yoda");
// assign elements to variables
extract($starwars);
// returns "Leia"
echo $princess;
?>