Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should i use isset? [duplicate]

Tags:

php

I'm beginner in PHP and was wondering what's the difference between this

$variable = "text"; 
if($variable){
    echo $variable; 
}

and this

$variable = "text"; 
if(isset($variable)){
    echo $variable; 
}
like image 841
Giorgi Avatar asked Dec 02 '25 07:12

Giorgi


2 Answers

Sometimes you want to know if a variable is set or not e.g. for security reasons of for debugging reasons.

The function isset() is used to determine if a variable is set and is not NULL and is accordingly returning true or false.

The expression if($variable) {} instead will evaluate to false if $variable is set but is zero or if $variable is set but its current value is false (=counterexample)

Assume:

isset($variable): Evaluates to true if a variable is set and not null

if($variable): Evaluates to true depending on the value of a variable or the result/value of an expression

like image 72
Blackbam Avatar answered Dec 04 '25 21:12

Blackbam


The most important feature of functions like isset(), empty(), etc. to me is, that they do not throw errors when a variable is not set, like Marc B already mentioned.

PS: I strongly recommend to turn on strict mode and all error reporting during development.

like image 31
schmunk Avatar answered Dec 04 '25 20:12

schmunk