简体   繁体   中英

how to check empty array from mysql in php

I have an array in php, this array is fetched from database. sometimes the array structure is like

array(""=>NULL)

but sometimes it's also contain actual data from the DB. but one thing for sure, it is never be an empty array (array())

how do i check if array is contain actual data?.

check that array size ==1 and it contains a "" array key and NULL is in the array.

Try like this:

   if(array_key_exists("",$array) && count($array) == 1 && in_array(NULL,$array)){
    echo "invalid";
   }

demo

if you are using mysql use mysql_num_rows() .. this will give you the count of fetched results from table .. so if the count is 0 than your array is empty....

or you are using PDO than use PDOstatement->rowCount() ... and if you are using mysqli than use mysqli_num_rows to get the count...

You can simply do this.

if ($arr) {
  // there was an error
} else {
  // there wasn't
}

According to PHP Manual the array to Boolean conversion will return false if the array contains only "NULL" as the value.

A very simple answer using php native functions

$input_array = array(""=>NULL);
$is_error=array_filter($input_array);
if (!empty($is_error)) {
    // do your stuff here
}

try this

if (!empty($result)
{
.....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM