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
count()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 isfalse. So as long as the variable is initializedif (!$row)will suffice.