Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

PHP: Checking if array is empty

Options
  • 16-01-2012 3:07pm
    #1
    Registered Users 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 Posts: 6,501 ✭✭✭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 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 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