Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

PHP: Checking if array is empty

  • 16-01-2012 03:07PM
    #1
    Registered Users, Registered Users 2 Posts: 1,757 ✭✭✭


    Hi all,

    I'm not a PHP developer but I am dabbling in it for my current project.
    I'm looking to print out if an array is empty after a check. After trawling loads of forums/sites for previous answers I can't find one that works in my situation.
    It's probably an easy solution :)

    Here's my code:

    [PHP]

    if ($db_found) {
    $SQL = "sql query...'";
    $result = mysql_query($SQL);

    while ($db_field = mysql_fetch_assoc($result)) {

    print "print stuff";
    }
    }

    [/PHP]

    The array should contain nothing because the query returns empty.
    I have tried these before and after the while loop:

    [PHP]
    if(count($result) == 0) {
    print "Array is empty";
    }
    [/PHP]

    and

    [PHP]
    if (empty($result)) {
    echo "Array is empty";
    }

    [/PHP]

    Thanks for any help guys :)


Comments

  • Registered Users, Registered Users 2 Posts: 6,651 ✭✭✭daymobrew


    $result is not an array it's a "resource"

    mysql_num_rows() returns the number of rows returned by a SELECT query.


  • Registered Users, Registered Users 2 Posts: 9,579 ✭✭✭Webmonkey


    Well from your code you are checking if you get results back from a database so maybe it's better to check the number of rows that are returned.

    [php]
    $result = mysql_query($SQL);
    if (mysql_num_rows($result) == 0) {
    echo "No results found";
    } else {
    while ($db_field = mysql_fetch_assoc($result)) {
    print "print stuff";
    }
    }
    [/php]


  • Registered Users, Registered Users 2 Posts: 1,757 ✭✭✭Deliverance XXV


    daymobrew wrote: »
    $result is not an array it's a "resource"

    mysql_num_rows() returns the number of rows returned by a SELECT query.

    Thanks for the info - that cleared it up a bit :)
    Webmonkey wrote: »
    Well from your code you are checking if you get results back from a database so maybe it's better to check the number of rows that are returned.

    [php]
    $result = mysql_query($SQL);
    if (mysql_num_rows($result) == 0) {
    echo "No results found";
    } else {
    while ($db_field = mysql_fetch_assoc($result)) {
    print "print stuff";
    }
    }
    [/php]

    Thanks, that code worked perfectly :)


Advertisement