1

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?.

5 Answers 5

2

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

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

Comments

1

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

6 Comments

Yes, use a deprecated method (no, don't really do this).
but he havent provided wether he is using mysql , mysqli or pdo.. Than I would have suggested different function..
I would update your answer to demonstrate the correct approach with both mysqli and PDO, and put your current answer underneath while flagging that it's deprecated.
PDO rowCount() is not reliable and its use is not suggested.
i forget to say that the value of the column is a serialized array. in select statement i select that field. i don't figure out yet why it always have count() > 0 (probably my bad coding). for now i use @Awlad Liton answer
|
0

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.

Comments

0

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
}

Comments

-1

try this

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

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.