PHP array FAQ: How do I iterate (loop) through a PHP array?
Answer: The easiest way to loop through a PHP array is to use the PHP foreach operator. If you have a simple one-dimensional array, like the $argv
array which lets you access command line arguments, you can loop through it like this:
#!/usr/bin/php <?php // loop through each element in the $argv array foreach($argv as $value) { echo "$value\n"; } ?>
If I save this file as argtest.php, and then run it, like this:
php argtest.php foo bar baz
I'll get the following output from the script:
argtest.php foo bar baz
I can also loop through a PHP array by accessing the array key and value, like this:
#!/usr/bin/php <?php // loop through each element in the $argv array foreach($argv as $key => $value) { echo "$key = $value\n"; } ?>
For this example, this array key/value approach results in the following output:
0 = argtest.php 1 = foo 2 = bar 3 = baz
Using the $argv array here isn't a great example of why you might want to access the array elements as key/value pairs, but I'm writing this article for myself, and all I really need is a reminder of this PHP foreach key/value syntax.
Okay, okay, this example makes more sense if you have a two-dimensional array like this:
$al = array( 'first_name' => 'Alvin', 'last_name' => 'Alexander' );