0

I need to be able to loop through a PHP object about 25 times, but using a foreach with an iteration counter doesn't get the job done. Can someone advise please?

Things I've Tried

$i = 0;

foreach($items as $item){
    if($i < 25){
        //do code here
    $i++;
    }else{
        break;
    }
}

this successfully counts through 1-25 and break but my code does not execute it just stops completely.

and i've also tried using a for loop but again this doesn't work. So what i really want to know is if there is a way to loop through a PHP object X amount of times before breaking out of the loop and carrying on with my code.

The reason i need this is because if i use "foreach" without limiting it, it will go through about 300 times which is way too much.

5
  • 2
    What is the desired output? Commented Feb 17, 2016 at 16:28
  • 1
    "my code does not execute it", execute what? Commented Feb 17, 2016 at 16:29
  • 1
    it's impossible!!!. No error in case. You need ensure your code in condition is correct Commented Feb 17, 2016 at 16:31
  • 1
    Maybe put the actual code instead of "do code here", we cannot guess what is the problem really.. also if iterating through whole collection is "way too much" maybe do not fetch all items from wherever they come from or slice the input (i.e. foreach (array_slice($items, 0, 25) as $item) { ... })? Commented Feb 17, 2016 at 16:35
  • @lupatus, Perfect just perfect, put that as the answer please. All i wanted to know what how to loop through an object X amount of times, so limiting the object to 25 values did what i needed thank you. Commented Feb 17, 2016 at 16:50

1 Answer 1

1

If iterating through whole collection is "way too much" maybe do not fetch all items from wherever they come from or slice the input

foreach (array_slice($items, 0, 25) as $item) {
     // do code here
}
Sign up to request clarification or add additional context in comments.

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.