Well, without seeing the code, so generally speaking, if you are going to separate them anyway, can you also do this in advance?
<?php // getting all the results. $products = $db->query('SELECT name FROM foo')->fetchAll(); $div1 = array_filter($products, function($product) { // condition which makes a result belong to div1. return substr('X', $product->name) !== false; }); $div2 = array_filter($products, function($product) { // condition which makes a result belong to div2. return substr('Y', $product->name) !== false; }); printf("%d elements in div1", count($div1)); printf("%d elements in div2", count($div2)); // then print the divs. No need for ifs here, because results are already filtered. echo '<div id="a">' . PHP_EOL; foreach( $div1 as $product ) { echo $product->name; } echo '</div>'; echo '<div id="b">' . PHP_EOL; foreach( $div2 as $product ) { echo $product->name; } echo '</div>';
That being said: you should pay attention to the comment, which says: βThis is usually faster in SQL,β because it is a more sensible approach if you want to filter the values.
EDIT : Changed the variable name to adapt the variable names in the sample code.
source share