note 110099 added to control-structures.foreach
| From: | MaxTheDragon at home dot nl | Date: | Wed, 19 Sep 2012 12:52:57 +0000 |
| Subject: | note 110099 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-190879@lists.php.net to get a copy of this message | ||
If you need to create an empty array before a foreach loop, for example because you're looping
through a set of database results and a result array is necessary to be filled up with
modified/filtered entries based on the database results, you could do this:
<?php
$results = array();
foreach($dbset as $entry) {
// Do something here.
$results[] = $something
}
?>
But if you care not for slightly less human-readable code, you could also write this in one line
thanks to the ternary operator (PHP >= 5.3):
<?php
foreach(($results = array()) ?: $dbset as $entry) {
// Do something here.
$results[] = $something
}
?>
Or (PHP < 5.3):
<?php
foreach(($results = array()) ?0: $dbset as $entry) {
// Do something here.
$results[] = $something
}
?>
This works firstly because foreach expects an array_expression before the as keyword, rather than a
variable, and secondly because an empty array evaluates to false, thus the second half of the
ternary statement is returned, which is the array to loop over. And because this expression is only
evaluated once to produce the array to loop over, the results array is not cleared every iteration.
Don't forget the parentheses around the assignment statement! This works for every language
construct that expects expressions.
----
Server IP: 83.137.20.135
Probable Submitter: 87.195.224.218
----
Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php
Edit -- https://master.php.net/note/edit/110099
Del: integrated -- https://master.php.net/note/delete/110099/integrated
Del: useless -- https://master.php.net/note/delete/110099/useless
Del: bad code -- https://master.php.net/note/delete/110099/bad+code
Del: spam -- https://master.php.net/note/delete/110099/spam
Del: non-english -- https://master.php.net/note/delete/110099/non-english
Del: in docs -- https://master.php.net/note/delete/110099/in+docs
Del: other reasons-- https://master.php.net/note/delete/110099
Reject -- https://master.php.net/note/reject/110099
Search -- https://master.php.net/manage/user-notes.php