PHP conditional error testing for value - php

Is $var==1 the proper syntax for testing whether $var has a value?
I ask, because I'm getting a failure on a simple conditional.
Here's the code that seems to be failing:
if ($slcustom31==1) {$page="http://www.mydomain.com/members/page_Alpha.php";}
I assume that there's something wrong with the syntax, $var==1 .
++++++++
Here's the entire conditional, if that makes things clearer:
//condition 1
if ($slcustom31==1) {$page="http://www.mydomain.com/members/page_Alpha.php";}
//condition2
elseif ($slcustom31!=1 AND $slcustom29!="") {$page="http://www.mydomain.com/members/".$slcustom29;}
//condition3
else {$page="http://www.mydomain.com/members/page_Beta.php";}
sl_redirecttourl($page);
SPECIFIC SYMPTOM:
Script ignores condition1 and condition2, defaults to condition3.
++++
And if it helps, here's the entire (short) script:
$groupswithaccess="somegroup";
require_once("../slpw/sitelokpw.php");
require_once("../slpw/sitelokapi.php"); //gets value being tested by conditional
if ($slcustom31==1) {$page="http://www.mydomain.com/members/page_Alpha.php";}
elseif ($slcustom31!=1 AND $slcustom29!="") {$page="http://www.mydomain.com/members/".$slcustom29;}//not finished, but started
else {$page="http://www.mydomain.com/members/page_Beta.php";}
sl_redirecttourl($page);
Can someone tell me what I should do differently?
Thanks!

if($var ==1){
//returns true only if var is 1
}
if(isset($var)){
//returns true if you currently have any value stored as the variable $var
}

No, you want to look at isset or empty.

To check if a variable has a value use:
empty($var);
If it's 'empty' it will return TRUE, and if not will return FALSE.
This is what's considered empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
Fore more info see: http://php.net/manual/en/function.empty.php

Related

PHP: is empty($var) equivalent to !$var

For validating a variable value we can do
if(empty($var)){
}
OR
This will return true on empty string, 0 as number, false, null
if(!$var){
}
What is the difference between this two approaches, are them equivalent?
EDIT: Some examples where they behave different will be more pratical.
EDIT2: The only difference founded from answers is that the second will throw a notice if $var is undefined. What about the boolean value they return?
EDIT3: for $var I mean any variable with any value, or even an undefined variable.
Conclusion from users answers:
if(!$var) and empty($var) are equivalent as described here http://php.net/manual/en/types.comparisons.php, they will return the same bool value on the same variable.
if(!$var) will return a php notice if $var is not defined, normally this is not the case (if we write good code) most IDEs will underline it.
When checking simple variables if(!$var) should be ok
When checking arrays index ($var['key']) or object properties ($var->key)
empty($var['key']) is better using empty.
the problem is that since !$vars is shorter than empty($vars) many of us will prefer the first way
You prefer the first one because it is a "shorter way"?
Shorter code does not mean better code, or faster scripts ;)
The speed of PHP functions and its various other behaviours is not determined by the length of the function name. It is determined by what PHP is actually doing to evaluate, action, and return results.
Besides that, don't choose methods based on length of code, choose methods based on scenario and best approach "for a given scenario".
Which is best depends on what you need, and there are other variable checks other than the two you mentioned (isset() for one).
but the problem is are they equivalent always
Not necessarily - see
http://php.net/manual/en/types.comparisons.php
Or create a quick test script to see what PHP returns for your two scenarios.
You could also be initialising your variables in your framework (or, likely, stand alone script), which means the scenario changes, as could your question and approach you use.
It's all contextual as to which is the best.
As for the required answer.
Anyway, to answer your question, here are some tests:
(!$vars)
Example code:
if ( !$vars )
{
echo "TRUE";
}
else
{
echo "FALSE";
}
will return:
Notice: Undefined variable: vars in /whatever/ on line X
TRUE
However, if you initialise the var in your scripts somewhere first:
$vars = "";
$vars = NULL;
$vars = 0;
Any of the above will return:
[no PHP notice]
TRUE
$vars = "anything";
will return:
FALSE
This is because with the exclamation mark you are testing if the var is FALSE, so when not initialised with a string the test script returns TRUE because it is NOT FALSE.
When we initialise it with a string then the var NOT being FALSE is FALSE.
empty($vars)
Example code:
if ( empty($vars) )
{
echo "TRUE";
}
else
{
echo "FALSE";
}
Not initialised/set at all, and all of the following:
$vars = "";
$vars = NULL;
$vars = 0;
will return:
TRUE
There is no PHP notice for using empty, so here we show a difference between the two options (and remember when I said the shortest code is not necessarily the "best"? Depends on the scenario etc.).
And as with the previous test:
$vars = "anything";
returns:
FALSE
This is the same with ( !$var ), you are testing IF EMPTY, and without the var being initialised at all, or with any "empty()" value: eg (""), or NULL, or zero (0), then testing if the var is empty is TRUE, so we get TRUE output.
You get FALSE when setting the var to a string because IS EMPTY = FALSE as we set it to something.
The difference is empty() does not throw a PHP notice when var is not defined, whereas (!$var) will.
Also, you may prefer it for being "shorter code", but if (!$var) isn't really much shorter/better looking than the widely used if (empty($var)).
But again, this depends on the scenario - PHP provides different options to suit different requirements.
No they are not equal
if(empty($var)){
echo "empty used\n";
}
if(!$var){ # line no. 6
echo "! used";
}
will output
empty used
Notice: Undefined variable: var in /var/www/html/test.php on line 6
! used
Following values are considered to be empty when using empty() function
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
As you can read in empty docs
empty() is essentially the concise equivalent to !isset($var) || $var
== false.
They are not.
The first one verify if $var has any value.
The second one verify as boolean - if true or not.
The second one will give you a notice, the first one will be true if the value is empty for $var.
If you wish to verify if $var exists, use isset.
if( !isset($var) )
echo '$var does not exists!<br>';
if(empty($var))
echo 'The value is empty or does not exists!<br>';
if( !$var )
echo 'Value is false!<br>';
$var = '';
if(empty($var))
echo 'The value is empty or does not exists!<br>';
Use this to view the notice
error_reporting(-1);
ini_set('display_errors', 1);
The main difference is that empty() will not complain if the variable does not exist, whereas using ! will generate a warning.
In older versions of PHP, empty() only worked on direct variables, meaning this would fail:
empty($a && $b);
This has been changed in 5.5
The official manual contains all you have to know on this subject:
http://php.net/manual/en/types.comparisons.php
if (!$var) is the last column, boolean : if($x) negated.
As you can see they are the same, but empty won't complain if the variable wasn't set.
From the manual:
empty() does not generate a warning if the variable does not exist
Take some time, and study that chart.
As far as I know, it's pretty simple.
empty() is basically equivalent to !isset($var) || !$var and does not throw any warnings/notices, whereas using just !$var will throw a notice if the variable isn't defined.
For the sake of completeness, the following are considered empty when using empty():
empty strings
empty arrays
0, 0.0, '0' (int, float, string)
null
false
defined variables without a value
From a boolean value return empty is equivaliend to !:
empty($var) === !$var; // supposed that $vars has been defined here
From a notice/waning notification they are not equivalent:
empty($array['somekey']); //will be silent if somekey does not exists
!$array['somekey']; // will through a warning if somekey does not exists

What is the most bulletproof way of checking a variable is not null or empty?

In PHP, What is the best way to check whether a string variable is empty or null?
I currently have the following:
if($variable == null || $variable == "")
exit;
And wondered if there was a more minimalistic way of doing this?
Thanks in advance
Use empty() see http://php.net/manual/en/function.empty.php
if(empty($myvariable))
exit();
Empty returns true if the variable is empty or null, full details below
From the doc
Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.
Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
The following things are considered to be empty (return true):
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
if (empty($variable))
exit;
You could also use is_null() if you wanted to explicitly test whether or not the variable was set to the value null.
http://www.php.net/manual/en/function.empty.php
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
For checking whether a variable is null or empty please refer the below code snippet
if(is_null($variable) || empty($variable))
{
exit;
}
For documentation about is_null and empty functions please refer the below urls
http://php.net/manual/en/function.is-null.php
http://www.php.net/manual/en/function.empty.php

How do I check if a $_GET parameter exists but has no value?

I want to check if the app parameter exists in the URL, but has no value.
Example:
my_url.php?app
I tried isset() and empty(), but don’t work. I’ve seen it done before and I forgot how.
Empty is correct. You want to use both is set and empty together
if(isset($_GET['app']) && !empty($_GET['app'])){
echo "App = ".$_GET['app'];
} else {
echo "App is empty";
}
empty should be working (if(empty($_GET[var]))...) as it checks the following:
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
Here are your alternatives:
is_null - Finds whether a variable is NULL
if(is_null($_GET[var])) ...
defined - Checks whether a given named constant exists
if(defined($_GET[var])) ...
if( isset($_GET['app']) && $_GET['app'] == "")
{
}
You can simply check that by array_key_exists('param', $_GET);.
Imagine this is your URL: http://example.com/file.php?param. It has the param query parameter, but it has not value. So its value would be null actually.
array_key_exists('param', $_GET); returns true if param exists; returns false if it doesn't exist at all.

PHP/MYSQL: check if variable is empty

I want to prevent an empty value from going into a MySQL database
I'm using following but for some reason it is letting the empty values get through...
if (trim($var)= '' || !isset($var)){
header("Location:page.php?er=novariablel");
}
else {
...insert into database
}
Note, there is a bunch of complicated stuff that sets the value of var which is why I want to have both the ='' and the !isset because either might be the case.
Am I missing something with the or statement, i.e. it evaluates to false if both are true. Or what am I doing wrong?
You're lacking an = for your Equal Comparison Operator inside your if statement. Try:
if (trim($var) == '' || !isset($var)){
Try:
if (!isset($var) || empty(trim($var))){
empty() is a better way to check to see if a variable has no value. Just keep in mind that the following will return true:
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
Try:
$var = trim($var);
if (!empty($var)){
//not empty
}
Try
if (strlen(trim($var)))==0
You should also have put a constraint in your database table attribute that it will not accept NULL values. Then your entry would have not been made in the database.
#John this is great advice.
empty(trim($var))
I've been programming for 6 years and I never thought of trimming the variable before checking to see if it's empty.

Should I use null to see if a variable is empty in PHP?

Which is better to use when I use _GET['something here'] for a variable to check if it is empty or not
if (isset($_GET['url']) != '') {
//do stuff with it
}
OR
if (isset($_GET['url']) != NULL) {
//do stuff with it
}
'' or null or something else?
Please don't call this over optimizing or micro optimizing, I am simply looking for best practices, thank you
Use empty() - it actually first test of the variable exists before testing whether something is in it.
[Edit: isset() returns only TRUE or FALSE, so both of the statements above work equally well]
You should do the following to be sure that the value both exists and isn't empty
if(isset($_POST[myField]) && $_POST[myField] != "") {
Do my PHP code
}
PHP can be a little painful when debugging blank/missing/empty value checks. You can use empty() or isset(), but remember the cases where empty returns true. It's highly liberal with what it considers empty.
Returns FALSE if var has a non-empty and non-zero value.
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
isset is more conservative in that it only checks for variable's existence and a NULL value. From the documentation:
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

Categories