if statement and functions - php

I sometimes see code that looks like this:
if(!Somefunction()){
// ...
}else{
// ...
}
I am more of a java developer and the only way I know the above statement holds is if the function returns a true or false at the end.
Does every function that is used in this format have to return a true or false? Or does this mean if the function is successfully executed?

No, not necessarily True or False. In PHP any variable can be converted to boolean.
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

Related

An expresstion in if statement should return TRUE or FALSE, but it runs a function. PHP

A newbie question.
Here is a function and an if statement.
<?php
function test(){
echo "somedata";
}
if(test())
?>
This code produces:
somedata
According to documentation an if expression should only return TRUE or FALSE, but apart of it, function runs. Why it happens?
PHP evaluates the if expression in order to know if the epression yields a truthy value or not. There is no other way to find out than to execute the functions that appear in the expression.
In this example it is very clear:
if (sqrt(4) > 1)
PHP must of course call the function sqrt, except that in this case it is a function without side-effects, while your function test also performs an echo. Secondly, it returns a value, while test doesn't. But that PHP can only find out by executing the function.
Note that the expression can in general return anything, but PHP has rules to what it considers truthy or falsy:
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
Every other value is considered TRUE (including any resource).
In case a function runs without executing a return statement, the returned value is null, so the if condition will be falsy according to the above rules.

Is IF(integer) valid in PHP? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Regarding if statements in PHP
In PHP scripts - what does an if statement like this check for?
<?php if($variable){ // code to be executed } ?>
I've seen it used in scripts several times, and now I really want to know what it "looks for". It's not missing anything; it's just a plain variable inside an if statement... I couldn't find any results about this, anywhere, so obviously I'll look stupid posting this.
The construct if ($variable) tests to see if $variable evaluates to any "truthy" value. It can be a boolean TRUE, or a non-empty, non-NULL value, or non-zero number. Have a look at the list of boolean evaluations in the PHP docs.
From the PHP documentation:
var_dump((bool) ""); // bool(false)
var_dump((bool) 1); // bool(true)
var_dump((bool) -2); // bool(true)
var_dump((bool) "foo"); // bool(true)
var_dump((bool) 2.3e5); // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array()); // bool(false)
var_dump((bool) "false"); // bool(true)
Note however that if ($variable) is not appropriate to use when testing if a variable or array key has been initialized. If it the variable or array key does not yet exist, this would result in an E_NOTICE Undefined variable $variable.
If converts $variable to a boolean, and acts according to the result of that conversion.
See the boolean docs for further information.
To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
The following list explains what is considered to evaluate to false in PHP:
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
Every other value is considered TRUE (including any resource).
source: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
In your question, a variable is evaluated inside the if() statement. If the variable is unset, it will evaluate to false according to the list above. If it is set, or has a value, it will evaluate to true, therefore executing the code inside the if() branch.
It checks whether $variable evaluates to true. There are a couple of normal values that evaluate to true, see the PHP type comparison tables.
if ( ) can contain any expression that ultimately evaluates to true or false.
if (true) // very direct
if (true == true) // true == true evaluates to true
if (true || true && true) // boils down to true
$foo = true;
if ($foo) // direct true
if ($foo == true) // you get the idea...
Any of these are considered to be false (so that //code to be executed would not run)
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
All other values should be true. More info at the PHP Booleans manual.
Try looking at this old extended "php truth table" to get your head around all the various potholes waiting to burst your tyres. When starting out be as explicit as you can with any comparison operator that fork your code. Try and test against things being identical rather that equal to.
It depends entirely on the value type of the object that you are checking against. In PHP each object type has a certain value that will return false if checked against. The explanation of these can be found here: http://php.net/manual/en/language.types.boolean.php Some values that evaluate to false are
float: 0.0
int: 0
boolean: false
string: ''
array: [] (empty)
object: object has 0 properties / is empty
NULL
Its a bit different from most other languages but once you get used to it it can be very handy. This is why you may see a lot of statements such as
$result = mysqli_multi_query($query) or die('Could not execute query');
A function in PHP need only return a value type that evaluates to false for something like this to work. The OR operator in PHP will not evaluated its second argument IF the first argument is true (as regardless of the second argument's output, the or statement will still pass) and lines like this will attempt to call a query and assign the result to $result. If the query fails and the function returns a false value, then the thread is killed and 'Could not execute query' is printed.
if a function successfully runs (true) or a variable exists (true) boolean the if statement will continue. Otherwise it will be ignored

PHP: if (!$val) VS if (empty($val)). Is there any difference?

I was wondering what's the difference the two cases below, and which one is recommended?
$val = 0;
if (!$val) {
//True
}
if (empty($val) {
//It's also True
}
Have a look at the PHP type comparison table.
If you check the table, you'll notice that for all cases, empty($x) is the same as !$x. So it comes down to handling uninitialised variables. !$x creates an E_NOTICE, whereas empty($x) does not.
If you use empty and the variable was never set/created, no warning/error will be thrown.
Let see:
empty documentation:
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)
Booleans documentation:
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
It seems the only difference (regarding the resulting value) is how a SimpleXML instance is handled. Everything else seems to give the same result (if you invert the boolean cast of course).

How exactly does if($variable) work? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Regarding if statements in PHP
In PHP scripts - what does an if statement like this check for?
<?php if($variable){ // code to be executed } ?>
I've seen it used in scripts several times, and now I really want to know what it "looks for". It's not missing anything; it's just a plain variable inside an if statement... I couldn't find any results about this, anywhere, so obviously I'll look stupid posting this.
The construct if ($variable) tests to see if $variable evaluates to any "truthy" value. It can be a boolean TRUE, or a non-empty, non-NULL value, or non-zero number. Have a look at the list of boolean evaluations in the PHP docs.
From the PHP documentation:
var_dump((bool) ""); // bool(false)
var_dump((bool) 1); // bool(true)
var_dump((bool) -2); // bool(true)
var_dump((bool) "foo"); // bool(true)
var_dump((bool) 2.3e5); // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array()); // bool(false)
var_dump((bool) "false"); // bool(true)
Note however that if ($variable) is not appropriate to use when testing if a variable or array key has been initialized. If it the variable or array key does not yet exist, this would result in an E_NOTICE Undefined variable $variable.
If converts $variable to a boolean, and acts according to the result of that conversion.
See the boolean docs for further information.
To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
The following list explains what is considered to evaluate to false in PHP:
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
Every other value is considered TRUE (including any resource).
source: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
In your question, a variable is evaluated inside the if() statement. If the variable is unset, it will evaluate to false according to the list above. If it is set, or has a value, it will evaluate to true, therefore executing the code inside the if() branch.
It checks whether $variable evaluates to true. There are a couple of normal values that evaluate to true, see the PHP type comparison tables.
if ( ) can contain any expression that ultimately evaluates to true or false.
if (true) // very direct
if (true == true) // true == true evaluates to true
if (true || true && true) // boils down to true
$foo = true;
if ($foo) // direct true
if ($foo == true) // you get the idea...
Any of these are considered to be false (so that //code to be executed would not run)
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
All other values should be true. More info at the PHP Booleans manual.
Try looking at this old extended "php truth table" to get your head around all the various potholes waiting to burst your tyres. When starting out be as explicit as you can with any comparison operator that fork your code. Try and test against things being identical rather that equal to.
It depends entirely on the value type of the object that you are checking against. In PHP each object type has a certain value that will return false if checked against. The explanation of these can be found here: http://php.net/manual/en/language.types.boolean.php Some values that evaluate to false are
float: 0.0
int: 0
boolean: false
string: ''
array: [] (empty)
object: object has 0 properties / is empty
NULL
Its a bit different from most other languages but once you get used to it it can be very handy. This is why you may see a lot of statements such as
$result = mysqli_multi_query($query) or die('Could not execute query');
A function in PHP need only return a value type that evaluates to false for something like this to work. The OR operator in PHP will not evaluated its second argument IF the first argument is true (as regardless of the second argument's output, the or statement will still pass) and lines like this will attempt to call a query and assign the result to $result. If the query fails and the function returns a false value, then the thread is killed and 'Could not execute query' is printed.
if a function successfully runs (true) or a variable exists (true) boolean the if statement will continue. Otherwise it will be ignored

How does php cast boolean variables?

How does php cast boolean variables?
I was trying to save a boolean value to an array:
$result["Users"]["is_login"] = true;
but when I use debug the is_login value is blank.
and when I do conditionals like:
if($result["Users"]["is_login"])
the conditions are always false.
Then i tried doing this:
$result["Users"]["is_login"] = "true";
and it worked.
It's not much of a big deal but when I'm returning boolean values from functions i still have to convert them to strings.
there is no cast
the
if($result["Users"]["is_login"])
should work.
can you try to use var_dump($result["Users"]["is_login"]); to make sure the variable has been set properly.
you can check is a variable is set or not by using the isset (manual) function.
Also you can find here how PHP evaluate the booleans:
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
Every other value is considered TRUE (including any resource).
No casting happens in your example.
Your problem is likely somewhere else.
Would you mind to share a more complete piece of code?
Try:
if((bool)$result["Users"]["is_login"] == true)
{
// do something
}
.
And reply to one of your encounter:
but when I use debug the is_login value is blank. and when I do conditionals like:
if($result["Users"]["is_login"])
since your return value is boolean value true, in PHP it doesn't have a representation for it, therefore appear as empty (mainwhile, if the value is a boolean false, then you'll see a 0

Categories