How can i limit a foreach() statement? Say i only want it to run the first 2 'eaches' or something?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
There are many ways, one is to use a counter:
Other way would be to slice the first 2 elements, this isn't as efficient though:
You could also do something like this (basically the same as the first foreach, but with for):
you should use the break statement
usually it's use this way
on the same fashion the continue statement exists if you need to skip some items.
this is best solution for me :)
In PHP 5.5+, you can do
Generators rock.
You can either use
or
(the second solution is even worse)