Image

PHP - Processing Arrays - Processing Arrays

Processing Arrays

Problem
You want to iteratively process the elements in an array.
Solution

Use a foreach() loop and appropriate temporary variables, depending on whether the array has numeric indices or string keys:

<?php
// define indexed array
$idxArr = array("John", "Joe", "Harry", "Sally", "Mona");
// process and print array elements one by one
// result: "John | Joe | Harry | Sally | Mona | "
foreach ($idxArr as $i) {
print "$i | ";
}
?>
<?php
// define associative array
$assocArr = array("UK" => "London", "US" => "Washington",↵
"FR" => "Paris", "IN" => "Delhi");
// process and print array elements one by one
// result: "UK: London US: Washington FR: Paris IN: Delhi "
foreach ($assocArr as $key=>$value) {
print "$key: $value";
print "<br />";
}
?>

Comments

PHP’s foreach() loop is the simplest way to iterate over an array. At each iteration, the current array element is assigned to a temporary variable