What does if (!$variablename) do in PHP? - 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 != ""){
}

Related

PHP: using empty() for empty string?

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

Php "" and 0 return same value

$page_now=array_search($id, $user_id);
if($page_now==""){return TURE;}
else{return FALSE}//include [0]index
I have an array_search, if it can't find the match it will return "",
However I have problem on [0] index
if the search index return 0 which is 1st one from array.
if statement $page_now=="" & $page_now==0 both are return TURE
Try this
$var=0;
if($var!=""){echo "have value in var";}else{echo "no value in var";}
I want it return have value even it is 0
This is a documented behavior:
http://php.net/array_search
http://php.net/manual/en/types.comparisons.php
http://www.php.net/manual/en/language.types.type-juggling.php
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.
Also make sure you are aware about this:
strict
If the third parameter strict is set to TRUE then the
array_search() function will search for identical elements in the
haystack. This means it will also check the types of the needle in the
haystack, and objects must be the same instance.
You should use strict comparison operator === if you don't want to fall into dark abyss of PHP weak-types comparisons:
php > var_dump(0 == "0afca13435"); // oops, password's hash check went wrong :)
bool(true)
php > var_dump(0 == false);
bool(true)
BUT:
php > var_dump(false == "0afca13435");
bool(false)
// Uh, oh :) that's because int and string comparison will cast string to int,
// and in php string->int cast will return either 0 or any numeric prefix the
// string contain; bool and string comparison will cast string to bool, and
// numeric prefix is no longer an issue
----------
php > var_dump(false == "");
bool(true)
php > var_dump(0 == "");
bool(true)
// WTF! :)
And with strict:
php > var_dump(0 === "0afca13435");
bool(false)
// ahh, much better
The function array_search() returns false if it can't find the match. So you should use strict comparison operator === and compare it with false:
if($page_now===false) {
return true;
}
else {
return false;
}
try this (the empty checks if the variable is empty (""(empty string), 0, false, null etc ) is counted as empty (and will trigger this)
your code is now not checking if something is empty you only check if it isn't "" and null etc. will be triggered as not empty.
if(empty($page_now)){
return true;
}else{
return false;
}
if it is allowed to be 0 you can use this
if(empty($page_now) && $page_now != 0){
return true;
}else{
return false;
}

PHP check if False or Null

I also get confused how to check if a variable is false/null when returned from a function.
When to use empty() and when to use isset() to check the condition ?
For returns from functions, you use neither isset nor empty, since those only work on variables and are simply there to test for possibly non-existing variables without triggering errors.
For function returns checking for the existence of variables is pointless, so just do:
if (!my_function()) {
// function returned a falsey value
}
To read about this in more detail, see The Definitive Guide To PHP's isset And empty.
Checking variable ( a few examples )
if(is_null($x) === true) // null
if($x === null) // null
if($x === false)
if(isset($x) === false) // variable undefined or null
if(empty($x) === true) // check if variable is empty (length of 0)
Isset() checks if a variable has a value including ( False , 0 , or Empty string) , But not NULL.
Returns TRUE if var exists; FALSE otherwise.
On the other hand the empty() function checks if the variable has an empty value empty string , 0, NULL ,or False. Returns FALSE if var has a non-empty and non-zero value.
ISSET checks the variable to see if it has been set, in other words, it checks to see if the variable is any value except NULL or not assigned a value. ISSET returns TRUE if the variable exists and has a value other than NULL. That means variables assigned a " ", 0, "0", or FALSE are set, and therefore are TRUE for ISSET.
EMPTY checks to see if a variable is empty. Empty is interpreted as: " " (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), and "$var;" (a variable declared, but without a value in a class.
isset — Determine if a variable is set and is not NULL
$a = "test";
$b = "anothertest";
var_dump(isset($a)); // TRUE
var_dump(isset($a, $b)); // TRUE
unset ($a);
var_dump(isset($a)); // FALSE
empty — Determine whether a variable is empty
<?php
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
echo '$var is set even though it is empty';
}
?>
It is important to use the correct function / notation, not just whatever appears to work correctly. There are a few things to consider that are not mentioned in the existing answers.
Use isset to check if a variable has either not been set or has been set to null.
Use empty to check if a variable == false. null is cast to false and as with isset, no notice is thrown if the variable has not been set.
if (!$variable) or if ($variable == false) is the same as empty, except that a notice will be thrown if the variable has not been set.
if ($variable !== null) is the same as isset, except that a notice will be thrown if the variable has not been set.
NB
if (!$variable) and if ($variable !== null) perform better than their respective functions but not when notices are being generated, therefore, $variable needs to have been set. Don't suppress notices as a micro-optimisation, as this will make your code harder to debug and even suppressed notices cause a performance penalty.
Coalescing operators
If you are checking a variable so that you can assign a value to it, then you should use ??, ?: instead of if statements.
??
?? assigns a value when not equal to null.
$variable = $a ?? $b is the same as:
if (isset($a))
$variable = $a;
else
$variable = $b;
?:
?: assigns a value when not == to false.
$variable = $a ?: $b is the same as:
if ($a)
$variable = $a;
else
$variable = $b;
but remember that a notice will be generated when $a has not been set. If $a might not have been set, you can use $variable = !empty($a) ? $a : $b; instead.
check false: if ($v === false)
check null: if (is_null($v))
empty() is an evil.It is slow,and when $v queals false,0,'0',array(),'',it will return true.if you need this kind of checking,you can use if ($v).

PHP: Are these statements equivalent? (file_exists())

Aren't these equivalent?
==SCRIPT A==
if (file_exists($file) == false) {
return false;
}
==SCRIPT B==
if(!file_exists($file)) {
return false;
}
Plain answer: Y E S
They evaluate to the same thing.
That first one might be even better suited like this:
if (file_exists($file) === false) { // === checks type and value
return false;
}
OR:
return file_exists($file);
yes, file_exists returns a boolean, so it's either true or false.
so you could return file_exists($file) as well...
If you are making boolean comparisons, then you would rather do this:
if (file_exists($file) === false) {
return false;
}
using the === operator, to ensure that what you are receiving is a variable of type boolean and of value equivalent to false.
Yes.
But if you would use:
if (file_exists($file) === false) {
return false;
}
then it would not be the same as:
if(!file_exists($file)) {
return false;
}
because in the first case it would check whether the value returned by function matches strictly to false, and in the second case the value returned by function would be evaluated to boolean value.
EDIT:
That is general rule.
But in case of file_exists() function, which returns boolean value, evaluating to boolean is not necessary, thus you can use strict condition and this will have the same result (but only in case you know the value will be either true or false.
If you're asking "what's the difference between the === and == operator" then:
'===' is a strict comparison that checks the types of both sides.
'==' is an 'equivalent to' comparison operator that will cast either side to the appropriate type if deemed necessary.
To expand, '==' can be used to check for 'falsey' values and '===' can be used to check for exact matches.
if (1 == TRUE) echo 'test';
>> "test"
if (1 === TRUE) echo 'test';
>>
If you're asking if there's any functional / practical difference between your two code blocks then no, there isn't and you should be returning as such: return file_exists($file);
Worth a read:
http://php.net/manual/en/language.operators.comparison.php

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