0

I have a foreach loop that runs perfectly without flaw.

foreach ($row AS $row) {
   echo $row['id'];
}

There are times that there are no rows returned. I want to echo out 'there are no rows'; when there are no rows. The problem is if I try to do something like as follows:

foreach ($row AS $row) {
    if (!isset($row['id'])) {
        echo 'there are no rows';
    } else {
        echo $row['id'];
    }
}

It never returns the echo "there are no rows". I assume this is because when there are no rows, the foreach loop doesn't run. The question becomes, how do I echo "there are no rows" if and only if there are no rows while not interfering with the foreach when there are rows.

I have also tried code such as:

$row1 = $stmt->fetch();
$row = $stmt->fetchAll();
    if (isset($row1['id'])) {
        foreach ($row AS $row) {

Still no luck

So the desired outcome would be something as follows:

When loop runs:
1
2
3
4

When loop doesn't run:
there are no rows
8
  • 4
    check before the loop Commented Sep 13, 2016 at 0:40
  • ... with count() Commented Sep 13, 2016 at 0:41
  • 2
    $row AS $row ? maybe $rows AS $row Commented Sep 13, 2016 at 0:43
  • @Deep I use $row AS $row all the time but that count() solution got me sorted :) Commented Sep 13, 2016 at 0:45
  • foreach($row as $row) means you overwrite the value of $row, by the way. Also whenever trying to understand truth in value in any language, you should look at the truth table. In PHP an empty array is false. So as long as the variable is initialized if (!$row) will suffice. Commented Sep 13, 2016 at 1:00

2 Answers 2

5

you should check before the loop like so

if(count($row)>0){
//foreach ...
}else{
echo 'no data';
}
Sign up to request clarification or add additional context in comments.

Comments

4

Test if the array is empty:

if (empty($row)) {
    echo "there are no rows";
} else {
    foreach($row as $row) {
        ...
    }
}

1 Comment

Although this works great for primitive arrays, it wouldn't apply to something implementing Traversable and Countable. Just something to keep in mind

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.