3

I have an array that gets processed through a foreach loop.

foreach($images as $imageChoices) {
    Do stuff here
}

How do I limit the loop to only process the first 4 items in the array?

2
  • don't use foreach, use for. For-Each, can you see it there? No limitation, runs for each item in array Commented Jan 18, 2012 at 8:52
  • for (when incrementing an integer for the keys) only works with $i-based, incrementally increasing array keys. The OP doesn't specify whether that's the case or not. Commented Jan 18, 2012 at 8:54

5 Answers 5

11

The array_slice() function can be used.

foreach(array_slice($images, 0, 4) as $imageChoices) { … }

This enables you to only loop over the values that you want, without keeping count of how many you have done so far.

Sign up to request clarification or add additional context in comments.

2 Comments

NB array_slice has an additional parameter to preserve keys.
Thanks @symcbean, though that parameter would be useless in this case.
2

You basically count each iteration with the $i and stop the loop with break when 4 is reached...

$i = 0;
foreach($images as $imageChoices) {
    //Do stuff here
    $i++;
    if($i >= 4 { break; }
}

Comments

1

You can do:

for($i=0; $i<count($images) && $i<4; $i++) {
  // Use $images[$i]
}

Comments

1

Use a counter variable and increase it's count on each loop.

Apply check according to counter value

something like below:

 $count=1;

  foreach($images as $imageChoices) {
   if($count <=4)
   {
        Do stuff here
   } 
   else
   {
       Jump outside of loop  break;
   }
    $count++;

  }

OR you can do same with for loop instead of foreach and also with some inbuilt PHP Array functions

for($i=0; $i<4; $i++) {
  // Use $images[$i]
}

1 Comment

the for($i=0; $i<4; $i++) {} method pre-supposes that the array elements are numbered 0,1,2,3...
0
function process()
{
  //Some stuff
}

process(current($imageChoices));
process(next($imageChoices));
process(next($imageChoices));
process(next($imageChoices));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.