Checking for a null value in conditional in PHP - php

I have found there to be multiple ways to check whether a function has correctly returned a value to the variable, for example:
Example I
$somevariable = '';
$somevariable = get_somevariable();
if ($somevariable)
{
// Do something because $somevariable is definitely not null or empty!
}
Example II
$somevariable = '';
$somevariable = get_somevariable();
if ($somevariable <> '')
{
// Do something because $somevariable is definitely not null or empty!
}
My question: what is the best practice for checking whether a variable is correct or not? Could it be different for different types of objects? For instance, if you are expecting $somevariable to be a number, would checking if it is an empty string help/post issues? What is you were to set $somevariable = 0; as its initial value?
I come from the strongly-typed world of C# so I am still trying to wrap my head around all of this.
William

It depends what you are looking for.
Check that the Variable is set:
if (isset($var))
{
echo "Var is set";
}
Checking for a number:
if (is_int($var))
{
echo "Var is a number";
}
Checking for a string:
if (is_string($var))
{
echo "var is a string";
}
Check if var contains a decimal place:
if (is_float($var))
{
echo "Var is float";
}
if you are wanting to check that the variable is not a certain type, Add: ! an exclamation mark. Example:
if (!isset($var)) // If variable is not set
{
echo "Var Is Not Set";
}
References:
http://www.php.net/manual/en/function.is-int.php
http://www.php.net/manual/en/function.is-string.php
http://www.php.net/manual/en/function.is-float.php
http://www.php.net/manual/en/function.isset.php

There is no definite answer since it depends on what the function is supposed to return, if properly documented.
For example, if the function fails by returning null, you can check using if (!is_null($retval)).
If the function fails by returning FALSE, use if ($retval !== FALSE).
If the function fails by not returning an integer value, if (is_int($retval)).
If the function fails by returning an empty string, you can use if (!empty($retval)).
and so on...

It depends on what your function may return. This kind of goes back to how to best structure functions. You should learn the PHP truth tables once and apply them. All the following things as considered falsey:
'' (empty string)
0
0.0
'0'
null
false
array() (empty array)
Everything else is truthy. If your function returns one of the above as "failed" return code and anything else as success, the most idiomatic check is:
if (!$value)
If the function may return both 0 and false (like strpos does, for example), you need to apply a more rigorous check:
if (strpos('foo', 'bar') !== false)
I'd always go with the shortest, most readable version that is not prone to false positives, which is typically if ($var)/if (!$var).

If you want to check whether is a number or not, you should make use of filter functions.
For example:
if (!filter_var($_GET['num'], FILTER_VALIDATE_INT)){
//not a number
}

Related

StrPos always returns False?

I've been working on a very basic search engine. It basically operates by checking if the word exists. If it does, it returns the link. I know most of you would suggest to create a database from phpMyAdmin but I don't remember the password to make the mySql_Connect command work.
Anyway here is the code:
<?php
session_start();
$searchInput = $_POST['search'];
var_dump($inputPage1);
var_dump($searchİnput);
$inputPage1 = $_SESSION['pOneText'];
$inputPage2 = isset($_SESSION['pTwoText']) ? $_SESSION['pTwoText'] : "";
$inputPage3 = isset($_SESSION['pThreeText']) ? $_SESSION['pThreeText'] : "";
if (strpos($inputPage1, $searchInput)) {
echo "True";
} else {
echo "False";
}
?>
When I search a word, any word from any page, weather it exists or not, it always returns false. Does anyone know why?
From the PHP documentation:
Warning: This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
So the function returns the integer 0 since $searchInput starts at the first character of $inputPage1. Since it is inside an if condition, that expects a boolean, the integer is then converted to one. When converted to boolean, zero is equal to false so instead the else block is executed.
To fix it, you need to use the !== operator (the not equal equivalent of ===):
if (strpos($inputPage1, $searchInput) !== false) {
//...
Try stripos() to match case insensitive
First print all items in $_POST and $_SESSION using
echo "<pre>";
print_r($_POST);
print_r($_SESSION);
and ensure that the search string really exist in the bigger string .
Also make sure that your are using "false" to compare :
i.e
$pos = strpos($biggerString,$seachString);
if($pos !== false)
{
echo "Not found";
}

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

Do all php types return a bool?

I'm currently building a website and I come across the case where I can do:
if (myString)
if (myArray),
and it seems to "return" true whenever there is data inside the variable. At least, that's what I think.
E.g.
$testVar = "test";
if ($testVar)
echo $testVar;
else
echo "Empty";
When i assert $testVar = "", then it echos "Empty".
I'm wondering if this is a defined feature of PHP, that any type will return true if it is not null or empty, as in other languages you need to do if($testVar = "") or so on.
Additionally, if this does indeed return true on all types if the variable is not empty, and I also want to check if the variable exists, would:
if (isset($testVar) && $testVar) be okay to use (in terms of practices)
I have searched for questions but can't find an answer to this exact question. To summarize:
Can any type return a bool, provided that it is not empty?
Thanks.
These types do not return true, but they are, instead, cast to true. PHP is a weak typed language, so it will automatically try to convert a variable to the correct type when required. In most instances, this means that a non-empty variable will return true.
This resource here will give you more information. Take a look at the "Converting to boolean" section, specifically.
http://www.php.net/manual/en/language.types.boolean.php
You can not check if a string is empty that way. Consider this:
$test = "0";
if ($test)
echo $test;
else
echo "Empty";
The code above prints "Empty", because "0" is a falsy value. See Booleans, section "Converting to boolean".
So the answer is:
All types can be converted to booleans, but the result might not be what you want.
The variables don't "return" a bool, but any variable can evaluate to either true or false.
Best practice is to be strict on your comparisons and not just do if($var)
For detailed comparison information, see: http://us3.php.net/manual/en/types.comparisons.php
conditional always return bool
if you need to check any empty values you need to use equalsto operator for check values
if($testVar == "") // check is $testVar is empty or not return bool-true/false
best to use functions like empty()
if(empty($testVar))
In this example when you are testing string variables:
$testVar = "test";
if ($testVar)
echo $testVar;
else
echo "Empty";
What you are asserting is if variable $testVar is set (not if it's empty or not). The variable themselves don't have a return type, but it's in the context they are used in a control flow operator such as an if statement.
i.e. if ($testVar) is same as if (isset($testVar)) (when $testVar is a string)
However, there are other cases like this:
$testVar = "0";
if ($testVar)
echo $testVar;
else
echo "Empty";
In this case, you will get "Empty" because $testVar is evaluated as a int 0.
However; if you had this:
$testVar = " 0"; // notice the space in front of 0
if ($testVar)
echo $testVar;
else
echo "Empty";
This will echo back the $testVar because the variable is both set and has a string value.
When you want to check for empty string, you have several options:
if (empty($testVar))
if (strlen($testVar)) or if (strlen($testVar) > 0) (both same)
etc...

What is the best way to know is $_GET['example']=="somevalue"?

if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
OR
if((!empty($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
OR just
if($_GET['example']=='somevalue'){ ... }
I am asking that why I have seen many example where people check first if $_GET['example'] is set and then if $_GET['example']=='somevalue' ( first and second example above ).
I don't understand why not just use the last solution ( if $_GET['example']=='somevalue' then $_GET['example'] is obviously set ).
This question refers to any other variable ( $_POST, $_SERVER, ecc ).
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
Is the right one, you want to know that the "variable" exists (or is set) in order to use it. Empty just checks wether it has data of any kind or not.
For example:
<?php
$foo= 0;
if (empty($foo)) { // True because $foo is empty
echo '$foo is either 0, empty, or not set at all';
}
if (isset($foo)) { // True because $foo is set
echo '$foo is set even though it is empty';
}
if (isset($var)) { // FALSE because $var was not declared before
...
}
?>
The differences between isset and empty are subtle but important. They are most relevant when used alone. If you are checking that a variable exists and is a truethy value (e.g. any string that is not all spaces or 0s) you can use either interchangeably.
When to use isset
Use isset when it's important to know if the variable has been defined and is not null:
if (isset($maybeExistsMaybeNull)) {
// variable defined and is not NULL
}
When to use !empty
Use !empty when it's important to know if the variable has be defined and is truthy
if (!empty($mightBeEmpty)) {
// variable defined, and isn't "", " ", 0, "0" etc.
}
!empty is a great shorthand for exists and is something.
When to use array_key_exists
Use array_key_exists when it's important to know if the key exists and the value is of no importance:
if (array_key_exists('something', $array)) {
// $array['something'] exists, could be literally anything including null
}
When not to use isset
If your code looks like this:
if (isset($something) && $something) {
// code is shorter with !empty
}
When not to use !empty
If your code looks like this:
if (!empty($something) && $something === "") {
// you meant isset. this is unreachable.
}
Then you're writing code that can't be executed
Code that throws errors is error prone
Avoid writing code that issues notices/warnings that you are ignoring. For example in the question:
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
The first use of example is an undeclared constant. Or is it undeclared - what if you've got define('example', "foo"); somewhere else in the code.
if($_GET['example']=='somevalue'){ ... }
If the url doesn't contain ?example=.. that's going to issue a notice too.
Writing code without displaying errors means you can very easily miss mistakes like the first.
In context: isset and !empty are equivalent
For the example given, these two language constructs act exactly the same.
There is no case where one will act differently than the other, neither will issue a notice if the variable is undefined, and no measurable difference in performance between the two.
As others have said for checking things like $_GET and $_POST you would ideally want to use:
if ( isset($_GET['example']) && $_GET['example'] =='somevalue' ) {
// process data
}
So you always want to firstly make sure that the variable has been set (and not set to null) or in other words exists. Then proceed to check if the variable contains the data that you were expecting. If you try to make reference to a variable which doesn't exist (by not checking isset()) php will give you a notice saying 'undefined variable...etc etc'.
If you wanted to find out if a variable is set but are not concerned too much by what then you could use:
if ( !empty($_GET['example']) ) {
// process data
}
But I would be careful about using empty() on strings in this regard as empty can behave strangely with string data like '0' or ' '.
So I would always do the first one, to a) make sure the variable exists and b) is what you were expecting it to be.
This is something that you'll probably do a lot of and it helps to put together a class/functions which handles this checking for you so you dont have to do it everytime.
function checkValue($key, $value) {
if(array_key_exists($key, $_REQUEST)){
if ($_REQUEST[$key] == $value) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I just use Request as a default instead of switching out (though it is preferable to switch in some cases between POST and GET for security (imo)).
Now you can just call this function anywhere
if (checkValue('Item', 'Tom') === true){} etc
the best is
if((isset($_GET[example]))&&('somevalue'==$_GET['example'])){ ... }
The difference between
'somevalue'==$_GET['example']
AND
$_GET['example']=='somevalue'
If you mistype the == and type = instead, the first notaion will raise an error to notify you.
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }

Better way to check variable for null or empty string?

Since PHP is a dynamic language what's the best way of checking to see if a provided field is empty?
I want to ensure that:
null is considered an empty string
a white space only string is considered empty
that "0" is not considered empty
This is what I've got so far:
$question = trim($_POST['question']);
if ("" === "$question") {
// Handle error here
}
There must be a simpler way of doing this?
// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
return ($str === null || trim($str) === '');
}
Old post but someone might need it as I did ;)
if (strlen($str) == 0){
do what ever
}
replace $str with your variable.
NULL and "" both return 0 when using strlen.
Use PHP's empty() function. 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 more details check empty function
I'll humbly accept if I'm wrong, but I tested on my own end and found that the following works for testing both string(0) "" and NULL valued variables:
if ( $question ) {
// Handle success here
}
Which could also be reversed to test for success as such:
if ( !$question ) {
// Handle error here
}
Beware false negatives from the trim() function — it performs a cast-to-string before trimming, and thus will return e.g. "Array" if you pass it an empty array. That may not be an issue, depending on how you process your data, but with the code you supply, a field named question[] could be supplied in the POST data and appear to be a non-empty string. Instead, I would suggest:
$question = $_POST['question'];
if (!is_string || ($question = trim($question))) {
// Handle error here
}
// If $question was a string, it will have been trimmed by this point
There is no better way but since it's an operation you usually do quite often, you'd better automatize the process.
Most frameworks offer a way to make arguments parsing an easy task. You can build you own object for that. Quick and dirty example :
class Request
{
// This is the spirit but you may want to make that cleaner :-)
function get($key, $default=null, $from=null)
{
if ($from) :
if (isset(${'_'.$from}[$key]));
return sanitize(${'_'.strtoupper($from)}[$key]); // didn't test that but it should work
else
if isset($_REQUEST[$key])
return sanitize($_REQUEST[$key]);
return $default;
}
// basics. Enforce it with filters according to your needs
function sanitize($data)
{
return addslashes(trim($data));
}
// your rules here
function isEmptyString($data)
{
return (trim($data) === "" or $data === null);
}
function exists($key) {}
function setFlash($name, $value) {}
[...]
}
$request = new Request();
$question= $request->get('question', '', 'post');
print $request->isEmptyString($question);
Symfony use that kind of sugar massively.
But you are talking about more than that, with your "// Handle error here
". You are mixing 2 jobs : getting the data and processing it. This is not the same at all.
There are other mechanisms you can use to validate data. Again, frameworks can show you best pratices.
Create objects that represent the data of your form, then attach processses and fall back to it. It sounds far more work that hacking a quick PHP script (and it is the first time), but it's reusable, flexible, and much less error prone since form validation with usual PHP tends to quickly become spaguetti code.
This one checks arrays and strings:
function is_set($val) {
if(is_array($val)) return !empty($val);
return strlen(trim($val)) ? true : false;
}
to be more robust (tabulation, return…), I define:
function is_not_empty_string($str) {
if (is_string($str) && trim($str, " \t\n\r\0") !== '')
return true;
else
return false;
}
// code to test
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
var_export($value);
if (is_not_empty_string($value))
print(" is a none empty string!\n");
else
print(" is not a string or is an empty string\n");
}
sources:
https://www.php.net/manual/en/function.is-string.php
https://www.php.net/manual/en/function.trim.php
When you want to check if a value is provided for a field, that field may be a string , an array, or undifined. So, the following is enough
function isSet($param)
{
return (is_array($param) && count($param)) || trim($param) !== '';
}
use this :
// check for null or empty
if (empty($var)) {
...
}
else {
...
}
empty() used to work for this, but the behavior of empty() has changed several times. As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. If you want to check for a lack of object properties, a very defensive method at the moment is:
if (is_object($theObject) && (count(get_object_vars($theObject)) > 0)) {

Categories