Confuse with empty, isset ,! Empty ,! Isset
I have the following which is not working as expected as it $_GET['category']
may be 0 as well.
if ( empty( $_GET['category'] ) ){
// do something
} else {
// do something else
}
How to overwrite this if statement to do 3 different things
- Do something if
$_GET['category']
it doesn't exist at all - Do something if
$_GET['category'] == 0
- Do something if
$_GET['category'] ==
something other than "doesn't exist" and 0.
I tried different combinations empty()
, !empty()
, isset()
, !isset()
, but I do not get the results I need. Maybe I'm wrong...
source to share
This is not very difficult to do: isset
this is the method you need.
if (!isset($_GET['category'])) {
// category isn't set
} elseif ($_GET['category'] === '0') {
// category is set to 0
} else {
// category is set to something other than 0
}
Note that I matched a string for exact equality '0'
because variables GET
and POST
are always strings (or sometimes arrays) and never loop when PHP first gets them.
source to share
if (!isset($_GET['category']))
{
1. Do something if $_GET['category'] does not exist at all
}
elseif ($_GET['category'] == 0)
{
2. Do something if $_GET['category'] == 0
}
elseif (isset($_GET['category']) && ($_GET['category'] != 0)
{
3. Do something if $_GET['category'] == something other than "does not exist" and 0.
}
My parentheses might be a little bit somewhere, but hopefully this helps you.
source to share
<?php
$bad_values = array(null, '', 'dirty word');
if(isset($_GET['xd']))
{
if(in_array($_GET['xd'], $bad_values, true))
{
// bad, it was null, empty or something else you think is not ok
}
else
{
// it fine, now check whether you got the zero. do a string comparison
if($_GET['xd'] == '0')
{
// you got the zero, yell at the user
}
else
{
// you got something else, it might be fine, it might be spoofed. use referential integrity to enforce data integrity in your db
}
}
}
else
{
// it wasn't even sent in the request, that falls under 1)
}
source to share