0

When I am displaying my array by using var_dump I get the following result:

 array(1) { [0]=> NULL }

I want to apply a condition that when my array has a null value it should do something. I have tried using array[0]== NULL and array[0]= NULL inside my condition but it does not work. Can anyone tell me what could be the correct condition for it?

2
  • 1
    if(is_null($array[0])) {}? By the way, == makes a comparison, = is an assignement (even in an if statement). Commented Sep 9, 2015 at 6:39
  • if(in_array(NULL, $yourArray){} Commented Sep 9, 2015 at 6:40

3 Answers 3

5

PHPs empty() checks if a variable doesn't exist or has a falsey value (like array(), 0, null, false, etc).

<?php
if (!empty($array[0])) {
  echo "Not empty";
} else {
  echo "empty";
}
 ?>

or by using is_null

<?php
if(is_null($array[0])) {
  echo "empty";
} else {
  echo "not empty";
}
?>

or

<?php
if($array[0] === NULL) {
echo "empty";
} else {
echo "not empty";
}
?>
Sign up to request clarification or add additional context in comments.

Comments

1

You can do it by several ways:

if(is_null($array[0])) {}

or

if(!isset($array[0])) {}

or

if($array[0] === null) {}

By the way, == makes a comparison, = is an assignment (even in an if statement) and === compares values and type.

1 Comment

Sorry, I thought you have error in syntax because of $ in Anik's answer. He just updated his answer. lol.
-1
$arr =  array();
if (!empty($arr)){
   //do your code
}
else {
  echo "Hey I'm empty";
}

3 Comments

This would tell if whole array is not empty or not. I don't need this.
Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually won't help the OP to understand their problem.
Is this your are expecting Marium? $arr = array ( 0 => 5, 2 => NULL, 3 => 'prabha', 'k' => "NULL", 'l' => NULL, 'm' => 'money' ); foreach ($arr as $key => $val) { if ($val==NULL) { echo 'null is : ' . $key . ' => ' . $val . "<br>"; } else { echo $key . ' => ' . $val . "<br>"; } }

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.