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";
        }
  }
1
  • 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 stackoverflow.com/questions/12859942/… Commented Dec 3, 2012 at 11:56

4 Answers 4

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.

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

2 Comments

Your awnser is correct. Unfortunatly it doesnt tell teslasimus how he should check it outside the loop.
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.
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
}

3 Comments

If that is what you want, yes, but probably OP wants to check if a record was fetched.
+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.
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.
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";
    }

Comments

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(
.........
}

Comments

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.