Although with PHP you can do many things in many different ways it doesn’t mean you will hammer a bolt just because you haven’t found the right key.
With that in mind, analyze what you want to do: "A condition within an iteration". What will that condition do? " It will filter a certain result before performing the routine on it".
So use the right or most appropriate tool for the task at hand: 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 );
}
);
$date, now has only five elements, from one to five.
"But I have to print everything"
Here is where the various possibilities come in. A cool thing would be to compute the difference of the input array for this filtered, with array_diff()
"But still I’ll have to iterate to print"
Only if you want to. Because a one-dimensional matrix can perfectly be 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 this is an example, I created two distinct, unordered lists, mainly to demonstrate that it works.
You are printing the same thing whether it is bigger q 5 or not
– Erlon Charles