You are trying to get the 10th element from an array having only, for example, 9 elements; You do not rely on the size of the target array, which may be less than your limit.
If I were trying to get a limited number of entries, I would get a snippet from $response->businesses and execute foreach through a slice:
$limit = isset($_POST['displayLimit']) ? $_POST['displayLimit'] : 10; foreach (array_slice($response->businesses, 0, $limit) as $business) { echo $business->name; }
The array_slice function has a good function: when $limit greater than the total number of array elements (starting with $offset , the second parameter of the function), it returns only the available elements. For example, if you execute array_slice([1, 2, 3, 4], 0, 100) , it returns [1, 2, 3, 4] - limit is 100, but the array has only 4 elements, so they are all returned and no elements are added to the array when slicing.
Another way:
$limit = isset($_POST['displayLimit']) ? $_POST['displayLimit'] : 10; $counter = 0; foreach ($response->businesses as $business) { echo $business->name; $counter++; if ($counter >= $limit) { break; } }
Here I just break the foreach when the limit is reached. And I will not have errors if I have less elements of the $limit array.
Another approach that inherits from your code:
$limit = isset($_POST['displayLimit']) ? $_POST['displayLimit'] : 10; for ($x = 0; $x < $limit; $x++) { if (!array_key_exists($x, $request->businesses)) { // We have reached the end of $request->businesses array, // so break "for" loop. break; } echo $business->name; }
In any case, you should rely on the size of the array, since it has a probability of being less than $limit , which will lead to some errors.