Paul Dessert
Paul Dessert

Reputation: 6389

Limit the number of items in an array

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?

Upvotes: 3

Views: 6497

Answers (5)

user319198
user319198

Reputation:

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]
}

Upvotes: 1

kuboslav
kuboslav

Reputation: 1460

function process()
{
  //Some stuff
}

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

Upvotes: 0

Anonymous
Anonymous

Reputation: 3689

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; }
}

Upvotes: 2

codaddict
codaddict

Reputation: 455460

You can do:

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

Upvotes: 1

salathe
salathe

Reputation: 51970

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.

Upvotes: 11

Related Questions