1

How to tell if a php array is empty? i tried different methods but it never gets to echo "no content";

while($row = mysql_fetch_array($result))
  {
        if(count($row['link']))
        {
                echo '<a id="link_' . $row['Id'] . '" href="' . $row['link'] . '" data="/short_info.php?id=' . $row['Id'] . '/">' . $row['title'] . '</a><div class="in...
        }
        else
        {
                echo "no content";
        }
  }
teslasimus
  • 1,238
  • 5
  • 15
  • 23
  • Be aware that the `mysql_xxx()` functions are considered obsolete and insecure. It is recommended to switch to using the newer `mysqli_xxx()` functions, or the PDO library instead. See http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-function-in-php – SDC Dec 03 '12 at 11:56

4 Answers4

9

It is never empty. But when data is exhausted, mysql_fetch_array returns false and your loop ends, so you're not going to see it in the loop, anyway.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
  • Your awnser is correct. Unfortunatly it doesnt tell teslasimus how he should check it outside the loop. – Hugo Delsing Dec 03 '12 at 11:51
  • 1
    Yes, I also find your answer useful. Strictly speaking, it is not even necessary to tell — you can handle no content situation if your loop body has never been executed. I am assuming the OP is acquainted with some programming basics, so what I was doing here is not doing programming for OP, but explaining the phenomenon. – Michael Krelin - hacker Dec 03 '12 at 11:54
5

$row is an array. $row['link'] is just a string. So you could you use:

if (strlen($row['link'])==0) {
  //do something
}

But if you want to check for no result (no data rows from mysql) then you could use:

if (mysql_num_rows($result)==0)
  echo "no content"
else {
  //your while loop
}
Hugo Delsing
  • 13,803
  • 5
  • 45
  • 72
  • If that is what you want, yes, but probably OP wants to check if a record was fetched. – GolezTrol Dec 03 '12 at 11:47
  • +1, I also think the OP wants to see if there's any content at all. Why doing it in the loop is beyond me. – Michael Krelin - hacker Dec 03 '12 at 11:55
  • 1
    I guess thats just basic knowledge. The difference between knowing what you write and trying to find the right parts from examples and tutorials. But thats what makes this site great, people tell you why you should do something and not just what to do. – Hugo Delsing Dec 03 '12 at 11:59
2

update your code like:

$num=mysql_num_rows($result);
    if ($num>0) {
        echo '$var is either 0, empty, or not set at all';
    }
    else{
        echo "no content";
    }
Uttam Kadam
  • 458
  • 1
  • 7
  • 20
1

if there is not any row returned from the query this code will never enter the while block because the condition is false .... you can write :

$num=mysql_num_rows($result);

this will return the rows num then you write :

if($num==0) {echo "no content";}
else
{
while(
.........
}
Shadi
  • 1,526
  • 3
  • 11
  • 14