简体   繁体   中英

Condition for null value in an array in php

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?

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";
}
?>

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.

$arr =  array();
if (!empty($arr)){
   //do your code
}
else {
  echo "Hey I'm empty";
}

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