PHP: using empty() for empty string? - php

I recently discovered this interesting article by Deceze.
But I'm a bit confused by one of its advises:
never use empty or isset for variables that should exist
Using empty() is not good choice to test if $foo = ''; is empty?

What he means is if you want to check if the string is empty then empty won't do that. Empty can mean false, 0, null. Anything 'falsy'.
E.g. these are all true:
<?php
$string = null;
if (empty($string)) {
echo "This is true";
}
$string = '';
if (empty($string)) {
echo "This is true";
}
$string = 0;
if (empty($string)) {
echo "This is true";
}
If you want to check if the string is an empty string you should do this check for '':
<?php
$string = '';
if (isset($string) && $string === '') {
echo "This is true";
}
$string = null;
if (isset($string) && $string === '') {
echo "This is false";
}

You should not use empty (or isset) if you expect $foo to exist. That means, if according to your program logic, $foo should exist at this point:
if ($foo === '')
Then do not do any of these:
if (isset($foo))
if (empty($foo))
These two language constructs suppress error reporting for undefined variables. That's their only job. That means, if you use isset or empty gratuitously, PHP won't tell you about problems in your code. For example:
$foo = $bar;
if (empty($føø)) ...
Hmm, why is this always true, even when $bar contains the expected value? Because you mistyped the variable name and you're checking the value of an undefined variable. Write it like this instead to let PHP help you:
if (!$føø) ...
Notice: undefined variable føø on line ...
The condition itself is the same, == false (!) and empty produce the same outcome for the same values.
How exactly to check for an empty string depends on what values you do or don't accept. Perhaps $foo === '' or strlen($foo) == 0 is the check you're looking for to ensure you have a string with something in it.

PHP's empty() can be used in many cases.
It works for checking:
if a string is blank
if a variable is undefined or null
And of course empty() is best for your case too.

Try using this php if function:
$retVal = (condition) ? a : b ;
where condition: $value == null
a: is the value to display if $value is null
b: is the actual value to display or any other value to be displayed when $value is not null
In case of further guidance, kindly comment

Related

Message: Trying to get property of non-object error in php [duplicate]

Is there in PHP something similar to JavaScript's:
alert(test || 'Hello');
So, when test is undefined or null we'll see Hello, otherwise - we'll see the value of test.
I tried similar syntax in PHP but it doesn't seem to be working right... Also I've got no idea how to google this problem..
thanks
Edit
I should probably add that I wanted to use it inside an array:
$arr = array($one || 'one?', $two || 'two?'); //This is wrong
But indeed, I can use the inline '? :' if statement here as well, thanks.
$arr = array(is_null($one) ? "one?" : $one, is_null($two) ? "two ?" : $two); //OK
you can do echo $test ?: 'hello';
This will echo $test if it is true and 'hello' otherwise.
Note it will throw a notice or strict error if $test is not set but...
This shouldn't be a problem since most servers are set to ignore these errors. Most frameworks have code that triggers these errors.
Edit: This is a classic Ternary Operator, but with the middle part left out. Available since PHP 5.3.
echo $test ? $test : 'hello'; // this is the same
echo $test ?: 'hello'; // as this one
This only checks for the truthiness of the first variable and not if it is undefined, in which case it triggers the E_NOTICE error. For the latter, check the PHP7 answer below (soon hopefully above).
From PHP 7 onwards you can use something called a coalesce operator which does exactly what you want without the E_NOTICE that ?: triggers.
To use it you use ?? which will check if the value on the left is set and not null.
$arr = array($one ?? 'one?', $two ?? 'two?');
See #Yamiko's answer below for a PHP7 solution https://stackoverflow.com/a/29217577/140413
echo (!$test) ? 'hello' : $test;
Or you can be a little more robust and do this
echo isset($test) ? $test : 'hello';
As per the latest version use this for the shorthand
$var = $value ?? "secondvalue";
One-liner. Super readable, works for regular variables, arrays and objects.
// standard variable string
$result = #$var_str ?: "default";
// missing array element
$result = #$var_arr["missing"] ?: "default";
// missing object member
$result = #$var_obj->missing ?: "default";
See it in action: Php Sandbox Demo
I'm very surprised this isn't suggested in the other answers:
echo isset($test) ? $test : 'hello';
From the docs isset($var) will return false if $var doesn't exist or is set to null.
The null coalesce operator from PHP 7 onwards, described by #Yamiko, is a syntax shortcut for the above.
In this case:
echo $test ?? 'hello';
If you want to create an array this way, array_map provides a more concise way to do this (depending on the number of elements in the array):
function defined_map($value, $default) {
return (!isset($value) || is_null($value)) ? $default : $value;
// or return $value ? $default : $value;
}
$values = array($one, $two);
$defaults = array('one', 'two');
$values = array_map('defined_map', $values, $defaults);
Just make sure you know which elements evaluate to false so you can apply the right test.
Since php7.4, you can use the null coalescing assignment, so that you can do
$arr = array($one ??= "one?", $two ??= "two ?");
See the docs here
There may be a better way, but this is the first thing that came to my mind:
echo (!$test) ? "Hello" : $test;
Null is false in PHP, therefore you can use ternary:
alert($test ? $test : 'Hello');
Edit:
This also holds for an empty string, since ternary uses the '===' equality rather than '=='
And empty or null string is false whether using the '===' or '==' operator. I really should test my answers first.
Well, expanding that notation you supplied means you come up with:
if (test) {
alert(test);
} else {
alert('Hello');
}
So it's just a simple if...else construct. In PHP, you can shorten simple if...else constructs as something called a 'ternary expression':
alert($test ? $test : 'Hello');
Obviously there is no equivalent to the JS alert function in PHP, but the construct is the same.
alert((test == null || test == undefined)?'hello':test);
I recently had the very same problem.This is how i solved it:
<?php if (empty($row['test'])) {
echo "Not Provided";}
else {
echo $row['test'];}?></h5></span></span>
</div>
Your value in the database is in variable $test..so if $test row is empty then echo Not Provided

What's different between "isset($string)" & "#$string" on PHP?

What's different between isset($string) and #$string in PHP ?
This works both ways, so what's the difference?
if(isset($string))
....
if(#$string)
....
isset is true if the given variable exists and is not null.
#$var is true if the value of $var is true in a loose comparison.*
!== null and == true matches different values.
In the case of #$var, if $var does not exist, an error will be generated internally and raised and its output suppressed through #. This is a much more expensive operation, and it may trigger custom defined error handlers on the way. Do not ever use it if there's an alternative.
* A non-existent variable's value is substituted by null, which equals false.
Using isset($str) is not the same as #$str.
isset($str) is true if $str is set and is not null.
#$str is true if $str is truthy.
Consider the following example:
$str = "0";
if (isset($str)) {
// This gets printed because $str is set
echo "Str is set" . PHP_EOL;
}
if (#$str) {
// This is NOT printed because $str is falsy
echo "Str is truthy" . PHP_EOL;
}
It should also be noted that #, in addition to being a bad habit, incurs a significant performance penalty.
Function isset() check variable and return true if variable exists. Sign # ignore error. Give almost the same values. Next code maybe show it:
if(isset($string))
print 1; // no print
if(#$string)
print 2; // no print
$string = false;
if(isset($string))
print 3; // print 3
if(#$string)
print 4; // no print

What does if (!$variablename) do in PHP?

I know that != is "not equal", but what does it mean when you have this:
if(!$something)
My first guess is something to do with exceptions, but a look around google did not return anything.
So what does this do?
Whatever is in the variable is converted to a Boolean (the variable itself of course remains intact), and then a NOT operation (!) is done on the resulting Boolean. The conversion will happen because ! is a Logical Operator and only works on Boolean values.
When converting to boolean, the following values are considered FALSE:
the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Tip: If the variable is not expected to be Boolean, you might want to use something more specific like isset($variable), empty($variable), $variable === '', etc. depending on what you want to check for. Check the manual for details.
It's the same as:
if((bool)$something != true) {
See: http://www.php.net/manual/en/control-structures.if.php
if (!$something) {
is an equivelent of
if ($something == false) {
Checks to see whether $something is falsy.
It just means "If not something".
if (!false) {
this_happens_because_not_false_is_true();
}
It converts the variable into boolean equivalent of the variable. This can be given in a few cases:
<?php
// Case 1: $variable is boolean
$variable = true;
$variable = !$variable; // Changes to false;
var_dump($variable); // bool(false)
// Case 2a: $variable is a positive integer
$variable = 5;
$variable = !$variable; // Changes to false;
var_dump($variable); // bool(false)
// Case 2b: $variable is an integer other than 0
$variable = 0;
$variable = !$variable; // Changes to false;
var_dump($variable); // bool(true)
// Case 2c: $variable is a negative integer
$variable = -5;
$variable = !$variable; // Changes to false;
var_dump($variable); // bool(false)
// Case 3a: $variable is string
$variable = "Hello";
$variable = !$variable; // Changes to false;
var_dump($variable); // bool(false)
// Case 3b: $variable is empty string
$variable = "";
$variable = !$variable; // Changes to false;
var_dump($variable); // bool(true)
?>
In short, it makes the opposite of the empty() function! :)
Hope this helps! :)
if(!$variable) is the same as if($variable == false) so it checks if $variable is false
Look at #bažmegakapa answer to see which values are considered false.
it check if !$something is false or you can understand it like (if not$something) then {//this will execute } and if $something is present then the this will not enter in the if
!$variable is the 'Not' logical operator
http://uk3.php.net/manual/en/language.operators.logical.php
it takes a boolean value and flips it. True becomes false and false becomes true.
Checks to see if $something is false.
I met following code once
if (!$this->error) {
return false;
} else {
return true;
}
I thought "if no error , why false?? Thats wrong!" Because i thought "!" operator equals "NOT".
And swaped returns. But everytime error condition codes ran.
Then learned. "!" operator converts variables to boolean. Empty variables converted to "false". And "if" statements with "!" operator run like that "if this boolean is false, return false, else return true.! :)
if($somethin == ""){
}
Or
if($somethin != ""){
}

php null value confusion in switch statement

I have the following php code that gives me an unexpected result:
$foo = NULL;
switch($foo)
{
case 0:
print "What?!";
}
I'd expect the result to be nothing, but it matches case 0. The php manual says that NULL is a non-value, so how can it equal 0?
The switch statement applies loose comparison which means that the following things are treated as equivalent to 0:
false
0
"0"
NULL
"any string"
""
beacuse php is not type strict language
$foo = NULL;
if( isset( $foo ) ) {
switch( $foo ) {
case 0:
print "WTF!!!";
}
}
This can be also written like
$foo = NULL;
switch( true )
{
case ( 0 === $foo ):
print "What?!";
default:
print "Default?!";
}
PHP is doing a type-coerced, weak comparison. You will need to do this instead:
$foo = NULL;
if ($foo === 0)
print "WTF!!!";
You can do what I did - it's lazy but it works.
Before running the switch, I checked if the value is null and, if so, changed it to something known:
IF ($foo==null) {
$foo == 99;
}
switch($foo)
{
case 99:
print "This is NULL"; break;
case 0:
print "What?!";
}
I'm assuming here, but it could be that the switch statement coerces the value of $foo when comparing to 0. To test this hypothesis, why don't you try adding this above the switch statement:
echo $foo == NULL;
This should echo 1 before the curse, if I'm correct...
EDIT: The inaccuracy is with my testing, and it was pointed out to me. Check the comments, if you are interested.
From what I've tested, the top answer is inaccurate.
It seems as though a PHP switch statement sees NULL as a "joker", and applies any case to it.
I tried with different numbers and with a string, and they all fired. Nothing there suggests it should be NULL, not even on PHP loose comparison.
So my suggestion is adding a case NULL: at the start, just as you add default at the end.
$foo = NULL;
switch($foo)
{
case NULL:
print "This is NULL"; break;
case 0:
print "What?!";
}
As of PHP 8, you can use the match expression:
The match expression branches evaluation based on an identity check of a value.
Similarly to a switch statement, a match expression has a subject expression that is compared against multiple alternatives.
Unlike switch, it will evaluate to a value much like ternary expressions. Unlike switch, the comparison is an identity check (===) rather than a weak equality check (==).
Match expressions are available as of PHP 8.0.0.
Per your example:
$foo = null;
$value = match($foo) {
0 => print('What?')
};
Will output:
Fatal error: Uncaught UnhandledMatchError: Unhandled match value of type null
So you can add a try/catch and handle it accordingly or add a default "catch-all":
$compare = null;
$value = match($compare) {
0 => print('What?'),
default => print('Default!')
};

In php, is 0 treated as empty?

Code will explain more:
$var = 0;
if (!empty($var)){
echo "Its not empty";
} else {
echo "Its empty";
}
The result returns "Its empty". I thought empty() will check if I already set the variable and have value inside. Why it returns "Its empty"??
http://php.net/empty
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)
Note that this is exactly the same list as for a coercion to Boolean false. empty is simply !isset($var) || !$var. Try isset instead.
I was wondering why nobody suggested the extremely handy Type comparison table. It answers every question about the common functions and compare operators.
A snippet:
Expression | empty($x)
----------------+--------
$x = ""; | true
$x = null | true
var $x; | true
$x is undefined | true
$x = array(); | true
$x = false; | true
$x = true; | false
$x = 1; | false
$x = 42; | false
$x = 0; | true
$x = -1; | false
$x = "1"; | false
$x = "0"; | true
$x = "-1"; | false
$x = "php"; | false
$x = "true"; | false
$x = "false"; | false
Along other cheatsheets, I always keep a hardcopy of this table on my desk in case I'm not sure
In case of numeric values you should use is_numeric function:
$var = 0;
if (is_numeric($var))
{
echo "Its not empty";
}
else
{
echo "Its empty";
}
Use strlen() instead.
I ran onto the same issue using 1/0 as possible values for some variables.
I am using if (strlen($_POST['myValue']) == 0) to test if there is a character or not in my variable.
I was recently caught with my pants down on this one as well. The issue we often deal with is unset variables - say a form element that may or may not have been there, but for many elements, 0 (or the string '0' which would come through the post more accurately, but still would be evaluated as "falsey") is a legitimate value say on a dropdown list.
using empty() first and then strlen() is your best best if you need this as well, as:
if(!empty($var) && strlen($var)){
echo '"$var" is present and has a non-falsey value!';
}
From a linguistic point of view empty has a meaning of without value. Like the others said you'll have to use isset() in order to check if a variable has been defined, which is what you do.
empty() returns true for everything that evaluates to FALSE, it is actually a 'not' (!) in disguise. I think you meant isset()
To accept 0 as a value in variable use isset
Check if variable is empty
$var = 0;
if ($var == '') {
echo "empty";
} else {
echo "not empty";
}
//output is empty
Check if variable is set
$var = 0;
if (isset($var)) {
echo "not empty";
} else {
echo "empty";
}
//output is not empty
It 's working for me!
//
if(isset($_POST['post_var'])&&$_POST['post_var']!==''){
echo $_POST['post_var'];
}
//results:
1 if $_POST['post_var']='1'
0 if $_POST['post_var']='0'
skip if $_POST['post_var']=''
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)
From PHP Manual
In your case $var is 0, so empty($var) will return true, you are negating the result before testing it, so the else block will run giving "Its empty" as output.
From manual:
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)
More: http://php.net/manual/en/function.empty.php
You need to use isset() to check whether value is set.
Actually isset just check if the variable sets or not.In this case if you want to check if your variable is really zero or empty you can use this example:
$myVar = '';
if (empty($myVar))
{
echo "Its empty";
}
echo "<br/>";
if ($myVar===0)
{
echo "also zero!";
}
just for notice $myVar==0 act like empty function.
if (empty($var) && $pieces[$var] != '0') {
//do something
}
In my case this code worked.
empty should mean empty .. whatever deceze says.
When I do
$var = '';
$var = '0';
I expect that var_dump(empty($var)); will return false.
if you are checking things in an array you always have to do isset($var) first.
use only ($_POST['input_field_name'])!=0 instead of !($_POST['input_field_name'])==0 then 0 is not treated as empty.
Not sure if there are still people looking for an explanation and a solution. The comments above say it all on the differences between TRUE / FALSE / 1 / 0.
I would just like to bring my 2 cents for the way to display the actual value.
BOOLEAN
If you're working with a Boolean datatype, you're looking for a TRUE vs. FALSE result; if you store it in MySQL, it will be stored as 1 resp. 0 (if I'm not mistaking, this is the same in your server's memory).
So to display the the value in PHP, you need to check if it is true (1) or false (0) and display whatever you want: "TRUE" or "FALSE" or possibly "1" or "0".
Attention, everything bigger (or different) than 0 will also be considered as TRUE in PHP. E.g.: 2, "abc", etc. will all return TRUE.
BIT, TINYINT
If you're working with a number datatype, the way it is stored is the same.
To display the value, you need to tell PHP to handle it as a number. The easiest way I found is to multiply it by 1.
proper example. just create int type field( example mobile number) in the database and submit an blank value for the following database through a form or just insert using SQL. what it will be saved in database 0 because it is int type and cannot be saved as blank or null. therefore it is empty but it will be saved as 0. so when you fetch data through PHP and check for the empty values. it is very useful and logically correct.
0.00, 0.000, 0.0000 .... 0.0...0 is also empty and the above example can also be used for storing different type of values in database like float, double, decimal( decimal have different variants like 0.000 and so on.

Categories