Bruce
Bruce

Reputation: 1071

PHP how to handle when there is no foreach loop?

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

Upvotes: 0

Views: 646

Answers (2)

Barmar
Barmar

Reputation: 781716

Test if the array is empty:

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

Upvotes: 4

user6763587
user6763587

Reputation:

you should check before the loop like so

if(count($row)>0){
//foreach ...
}else{
echo 'no data';
}

Upvotes: 5

Related Questions