isset() and empty() - what to use
P粉165522886
P粉165522886 2023-10-16 20:54:57
0
2
592

Can you help me improve my coding style? :) In some tasks I need to check - if a variable is empty or contains something. To solve this task, I usually do the following.

Check - Is this variable already set? If it is set - I check - is it empty?

<?php
    $var = '23';
    if (isset($var)&&!empty($var)){
        echo 'not empty';
    }else{
        echo 'is not set or empty';
    }
?>

I have a question - should I use isset() before empty() - is it necessary? TIA!

P粉165522886
P粉165522886

reply all(2)
P粉514458863

In your specific case: if ($var).

If you don't know if the variable exists , you need to use isset. Since you declared it on the first line, you know it exists, so you don't need to, and no, shouldn't use isset.

The same is true for empty, except that empty is also combined with a check on the authenticity of the value. empty is equivalent to !isset($var) || !$var and !empty is equivalent to isset($var) && $var or isset($var) && $var == correct .

If you just want to test the authenticity of a variable that should exist , if ($var) is completely sufficient. .

P粉458913655

It depends on what you are looking for, if you just want to see if it is empty use empty as it will also check if it is set if you want to know if something is already set Set the setting or not using isset.

Empty Check whether the variable has been set. If it is set, check whether the variable is null, "", 0, etc.

Isset Just checks if it is set, it can be anything that is not empty

For empty, the following is considered empty:

  • ""(empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a floating point number)
  • "0" (0 as string)
  • null
  • mistake
  • array()(empty array)
  • var $var; (a variable is declared but has no value in the class)

From http://php.net/manual/en/function.empty.php


As mentioned in the comments, the lack of warnings is also important for empty()

PHP Manualsays

About the question

PHP Manualsays


Your code will do:


For example:

$var = "";

if(empty($var)) // true because "" is considered empty
 {...}
if(isset($var)) //true because var is set 
 {...}

if(empty($otherVar)) //true because $otherVar is null
 {...}
if(isset($otherVar)) //false because $otherVar is not set 
 {...}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template