note 110099 deleted from control-structures.foreach by googleguy

From: Date: Thu, 20 Sep 2012 00:24:41 +0000
Subject: note 110099 deleted from control-structures.foreach by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-190892@lists.php.net to get a copy of this message
Note Submitter: MaxTheDragon at home dot nl ---- 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.

« previous php.notes (#190892) next »