| Newsgroups |
php.notes |
| Message-ID |
<[email protected]> |
As well as numerically-indexed arrays, nested associative arrays can also be unnested in the foreach()
<?php
$records = [
['name' => 'Alice', 'address' => '...'],
['name' => 'Bob', 'address' => '...'],
['name' => 'Chris', 'address' => '...'],
...];
foreach($records as ['name' => $name]) {
echo "$name\n";
}
foreach($records as ['address' => $address, 'name' => $name]) {
echo "$name @ $address\n";
}
?>
The usual warnings about undefined array keys will occur if any of the element arrays lack the requested key.
One additional detail, the key is still just an ordinary string-valued expression, so...
<?php
$field = 'address';
foreach($records as [$field => $value]) {
echo "$value\n";
}
?>
If the value of $field changed within the loop, the new field would be accessed in subsequent iterations.
----
Server IP: 206.189.2.9
Probable Submitter: 122.57.27.239
----
Manual Page -- https://php.net/manual/en/control-structures.foreach.php
Edit -- https://main.php.net/note/edit/130572
Del: integrated -- https://main.php.net/note/delete/130572/integrated
Del: useless -- https://main.php.net/note/delete/130572/useless
Del: bad code -- https://main.php.net/note/delete/130572/bad+code
Del: spam -- https://main.php.net/note/delete/130572/spam
Del: non-english -- https://main.php.net/note/delete/130572/non-english
Del: in docs -- https://main.php.net/note/delete/130572/in+docs
Del: other reasons-- https://main.php.net/note/delete/130572
Reject -- https://main.php.net/note/reject/130572
Search -- https://main.php.net/manage/user-notes.php