search

Home  >  Q&A  >  body text

isset() and empty() - what to use

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粉165522886P粉165522886446 days ago576

reply all(2)I'll reply

  • P粉514458863

    P粉5144588632023-10-17 19:55:24

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

    reply
    0
  • P粉458913655

    P粉4589136552023-10-17 12:42:26

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

    reply
    0
  • Cancelreply