How to Limit Foreach Loop to a Number of Loops in PHP
Most of the time when we create a foreach loop, we'll want to proceed all elements of object/array being evaluated. Now, how if we want to limit a foreach loop to a number of loops? I will share how we could achive that.
To limit foreach loop, we'll need help from this PHP function:
array_slice. From the description in PHP Manual, this function
array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.
Let's say we have an array
$boxes which contains five elements. We want to process only three of them.
// We have boxes of fruits
$boxes = array(
array('label' => 'apples'),
array('label' => 'oranges'),
array('label' => 'bananas'),
array('label' => 'grapes'),
array('label' => 'watermelons'),
// Show only the first three boxes
foreach(array_slice($boxes, 0, 3) as $box)
// Print box labels
Above code will output:
I hope that you now know how to limit foreach loop to a number of loops in PHP. If you run into any issues or have any feedback feel free to drop a comment below.