0

I'm trying to get this function to work but for some reason it errors out on the foreach line saying there is an invalid argument.

$scores= TESTAPI::GUL($user->ID);
if (empty($scores)) {
    echo "<p>No Scores</p>";
} else {
    foreach ($scores as $score) {
        echo "<p>".$score."</p>";
    }
}

The error I get is: PHP Warning: Invalid argument supplied for foreach()

1
  • 2
    Add var_dump($scores); before the foreach line. What is the output? Commented Apr 16, 2015 at 9:20

4 Answers 4

2

For example, empty('') would also be true.

I would recommend to check is_array($scores) && count($scores) instead of empty(), to make sure the api returned useable output (an array) and that this contains elements (count() > 0 which is true).

Sign up to request clarification or add additional context in comments.

Comments

1
$scores = TESTAPI::GUL($user->ID);

if (is_array($scores) && count($scores)) {
    foreach ($scores as $score) {
        echo "<p>".$score."</p>";
    }
} else {
    echo "<p>No Scores</p>";
}

3 Comments

I did the following using similar to what you put and it works perfectly: if(!is_array($scores) && !count($scores)){
Be careful, expression (!is_array($scores) && !count($scores)) will also be true if $scores=false, so you might get unexpected results.
Perfectly fine answer. I'd just like to add that && count($scores) can safely be removed - if it's an empty array, the loop will not be entered anyways.
1

Try this -

 foreach ((array) $scores as $score) { ...

1 Comment

Just as a general notice: Type casting to an array could have unwanted side effects, e.g. if a value is an object.
1

Looks like $scores is neither an array nor an object...

2 Comments

Can you provide some additional context such as documentation to support this theory?

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.