Why use isset()

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
BDKR
DevNet Resident
Posts: 1207
Joined: Sat Jun 08, 2002 1:24 pm
Location: Florida
Contact:

Post by BDKR »

Coco wrote:(tho empty returns true if the value is 0 OR null)
Which I feel is crazy and incredibly vauge. 0 and null are not the same. 0 is a value. null isn't.
User avatar
evilmonkey
Forum Regular
Posts: 823
Joined: Sun Oct 06, 2002 1:24 pm
Location: Toronto, Canada

Post by evilmonkey »

nielsene wrote:
evilmonkey wrote:

Code: Select all

$var=$_GET['somevar'];
if (isset($var)){
//do something
}
else {
//do something else
}
Using that code, you will always "do something" and never "do something else"
$var is always set (its value might be empty, but....)

You would want to do

Code: Select all

if (isset($_GET['somevar']))
i.e. you can't assign to a variable and expect it to be unset.....
Well, I rely on globals anyway :P
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

Coco wrote:(tho empty returns true if the value is 0 OR null)
Also, and rather strangely, $var = '0'; is held to be empty by php as well as $var = 0 ..
User avatar
BDKR
DevNet Resident
Posts: 1207
Joined: Sat Jun 08, 2002 1:24 pm
Location: Florida
Contact:

Post by BDKR »

McGruff wrote:
Coco wrote:(tho empty returns true if the value is 0 OR null)
Also, and rather strangely, $var = '0'; is held to be empty by php as well as $var = 0 ..
That's why this thread can be summed up as:

1) Decide if you need to know if a variable is set or empty first.
2) If you just need to know if it's empty, decide what you think empty is.
3) Then test.

With checking forms, you don't allways know if the bloke on the other side entered something into a field. It's better to see if the var is set first, but even this isn't enough. What I've take to doing is something like the below...

Code: Select all

if( isset($_POST['blokes_name']) && !empty($_POST['blokes_name']) )
  { /* Do somethin' about it! */ }
However, this isn't perfect by any stretch! What the blokes name is 0? I could forcefully cast the var to being a string, but what if the var isn't set in the first place?

See how the logic starts getting convoluted?

Cheers,
BDKR
Coco
Forum Contributor
Posts: 339
Joined: Sat Sep 07, 2002 5:28 am
Location: Leeds, UK
Contact:

Post by Coco »

thats why i prefer is_null()
Post Reply