Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weak typing in PHP: why use isset at all?

Tags:

syntax

php

It seems like my code works to check for null if I do

if ($tx) 

or

if (isset($tx))

why would I do the second one when it's harder to write?

like image 574
Dan Rosenstark Avatar asked Jan 05 '09 17:01

Dan Rosenstark


People also ask

Why do we use isset in PHP?

Definition and Usage The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

Why isset () is required explain with example when we need to use Isset?

The isset() function is a built-in function of PHP, which is used to determine that a variable is set or not. If a variable is considered set, means the variable is declared and has a different value from the NULL. In short, it checks that the variable is declared and not null.

What can I use instead of isset in PHP?

The equivalent of isset($var) for a function return value is func() === null . isset basically does a !== null comparison, without throwing an error if the tested variable does not exist.

Should I use isset?

isset() is best for radios/checkboxes. Use empty() for strings/integer inputs. when a variable contains a value, using isset() will always be true. you set the variable yourself, so it's not a problem.


1 Answers

if ($tx)

This code will evaluate to false for any of the following conditions:

unset($tx); // not set, will also produce E_WARNING
$tx = null;
$tx = 0;
$tx = '0';
$tx = false;
$tx = array();

The code below will only evaluate to false under the following conditions:

if (isset($tx))

// False under following conditions:
unset($tx); // not set, no warning produced
$tx = null;

For some people, typing is very important. However, PHP by design is very flexible with variable types. That is why the Variable Handling Functions have been created.

like image 102
matpie Avatar answered Oct 05 '22 21:10

matpie