Although with PHP you can do many things in many different ways this does not mean that you will hammer a screw just because you did not find the right one.
With this in mind, consider what you want to do: "A condition within an iteration". What will this condition do? "It will filter a certain result before running the routine on it."
So, use the right or most appropriate tool for the task in question: array_filter ()
This function will receive a given input array and filter it according to the function passed as the second argument. This function can be a string for some function known to the program (such as a native function, for example), an anonymous function, or even an object method.
$data = array( 1,2,3,4,5,6,7,8,9,10 );
$data = array_filter(
$data,
function( $current ) {
return ( $current <= 5 );
}
);
$ data , now has only five elements, one to five.
"But I have to print everything"
Here is where the various possibilities come in. One cool thing would be to compute the difference of the input array for this filtering, with array_diff ()
"But I still have to iterate to print"
Only if you want. Because a one-dimensional array can be perfectly printed with implode()
, with HTML and everything:
$data = array( 1,2,3,4,5,6,7,8,9,10 );
$lowerThanFive = array_filter(
$data,
function( $current ) {
return ( $current <= 5 );
}
);
printf(
"<ul>\n <li>%s</li>\n</ul>",
implode( "</li>\n <li>", $lowerThanFive )
);
printf(
"\n\n<ul>\n <li>%s</li>\n</ul>",
implode( "</li>\n <li>", array_diff( $data, $lowerThanFive ) )
);
Note that because it is an example, I have created two distinct non-ordered lists, mainly to demonstrate that it works.