Using foreach loops on an associative array.
foreach can take each array as a key:value pair.
Syntax:
foreach ($array as $key => $value){
code to be executed;
}
The $key is the $position of the object in the $array. In the array below, the number 4 ($value) is in position zero, 8 ($value) is in position one, etc.
Example:
$ages = array(4, 8, 15, 16, 23, 42);
foreach($ages as $position => $value) {
echo $position . ": " . $value;
}
Output:
0: 4
1: 8
2: 15
3: 16
4: 23
5: 42
Another example with strings and integers in the associative array:
$prices = array("Brand New Computer" => 2000, "1 month in Lynda.com Training Library" => 25, "Learning PHP" => "priceless");
foreach($prices as $key => $value) {
if (is_int($value)) { //is_int looks for integers.
echo $key . ": $" . $value . ".00";
}
else {
echo $key . ": " . $value; //If not an integer then just print it.
}
}
Output:
Brand New Computer: $2000.00
1 month in Lynda.com Training Library: $25.00
Learning PHP: priceless
Multi-Dimensional Arrays
print_r($rows);
Array
(
[0] => Array
(
[TABLE_NAME] => vw_customer_display_nodocs
[IS_UPDATABLE] => YES
)
[1] => Array
(
[TABLE_NAME] => vw_ffl_book1
[IS_UPDATABLE] => YES
)
[2] => Array
(
[TABLE_NAME] => vw_ffl_book2
[IS_UPDATABLE] => YES
)
[3] => Array
(
[TABLE_NAME] => vw_ffl_bustax_docs
[IS_UPDATABLE] => YES
)
[4] => Array
(
[TABLE_NAME] => vw_ffl_license_docs
[IS_UPDATABLE] => YES
)
[5] => Array
(
[TABLE_NAME] => vw_ffl_ntn_inv_num
[IS_UPDATABLE] => YES
)
[6] => Array
(
[TABLE_NAME] => vw_ffl_weapondocs
[IS_UPDATABLE] => YES
)
[7] => Array
(
[TABLE_NAME] => vw_fflbook_transaction_number
[IS_UPDATABLE] => YES
)
[8] => Array
(
[TABLE_NAME] => vw_ffl_not_disposed
[IS_UPDATABLE] => YES
)
[9] => Array
(
[TABLE_NAME] => vw_ffl_disposed
[IS_UPDATABLE] => YES
)
)
echo $rows[0]['TABLE_NAME'] . "\r\n";
foreach ($rows[0] as $key[0] => $value) {
echo "$key[0]: $value\n";
}
function myfunction($value,$key)
{
echo "The key $key has the value $value.\r\n";
}
$i=count($rows);
for($x = 0; $x < $i; $x++){
array_walk($rows[$x],"myfunction");
}
$i=count($rows);
for($x = 0; $x < $i; $x++){
foreach($rows[$x] as $key => $value){
echo "$key: $value \r\n";
}
}
$i=count($rows);
for($x = 0; $x < $i; $x++){
echo $rows[$x]['TABLE_NAME'] . " " . $rows[$x]['IS_UPDATABLE'] . "\r\n";
}