John Doo
John Doo

Reputation: 119

How to limit foreach loop

This is my foreach code

foreach ($response3["keywords"] as $genreObject) {
             $keywords_name = $genreObject["name"];
             $stmt->execute();
         }

Any better way to limit the loop without this?

if ($i++ == 10) break;

Upvotes: 2

Views: 2778

Answers (2)

Geoff Taylor
Geoff Taylor

Reputation: 524

Personally I find the lost of readability to not be a big deal when the code's documentation is well written. You could do this.

<?php
     $i=0;
     while($i<10 && $keyword = $response3["keywords"][$i++]; ) {
         $keywords_name = $keyword["name"];
         $stmt->execute();
     }

It doesn't look as neat as the array_slice() w/ foreach loop but that would result in a new array being made which doesn't really matter unless it's a particularly long and heavy script

Upvotes: 1

arkascha
arkascha

Reputation: 42885

You can limit the actual array the loop iterates over:

<?php
foreach (array_slice($response3["keywords"], 0, 10) as $genreObject) {
    $keywords_name = $genreObject["name"];
    $stmt->execute();
}

Or, if the array is a straight numerically indexed one, you can use a for loop which is more efficient:

<?php
for ($i=0; $i<=10; $i++) {
    $keywords_name = $response3["keywords"][$i]["name"];
    $stmt->execute();
}

Upvotes: 6

Related Questions