I am working with the Zillow API to return reviews for a list of Agents. I have a foreach
loop that then pulls the list of reviews for each agent. The list is returned as JSON. I then run a foreach
loop on the JSON results to display the reviews individually. Everything works great except, a specific agent only has 1 review and it is throwing a foreach
error.
Here is a very simple example return:
If an agent has multiple reviews:
array(
[0] => Array (
[reviewer] => name,
[reviewerLink] => link
),
[1] => Array (
[reviewer] => name,
[reviewerLink => link
)
)
If an agent only has one review:
array([reviewer] => name [reviewerLink] => link)
I have tried using count()
, but on an array with only 1 review, it counts the total keys since there is no index.
I need a simple way to differentiate the arrays so I don't use a foreach
loop on the agents with only 1 review.
Is there a way to force the array to have an index? Or another way to differentiate the arrays?
If you have only one review, the key reviewer
exists. So you can check it with the function array_key_exists
if you have only one or more.
Try this code example:
if (array_key_exists('reviewer', $array)) {
// only one review
} else {
// more reviews
// do the foreach
}