what does ($variable) return? - php

just doing some validation and wanted to learn really what this meant instead of it just working.
Lets say i have:
$email = $_POST['email'];
if(!$email) {
echo 'email empty'
}
Whats is just having the variable and no check for it = something mean?
I thought
$variable
by its self meant that it returned that variable as true.
So i am also using if
!$variable
is means false.
Just wanted to clear up the actual meaning behind just using the variable itself.
Is it also bad practice to compare the variable for being empty?
So is it better to use
$email == ''
Than
!$email
Sorry if its a small question without a real answer to be solved, just like to 100% understand how what i am coding actually works.

PHP evaluates if $email is "truthy" using the rules defined at http://www.php.net/manual/en/language.types.boolean.php.
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
PS $email= '' will assign '' to $email.

$email = '' will empty the variable. You can use == or === instead.
In this case, it's better to use PHP's isset() function (documentation). The function is testing whether a variable is set and not NULL.

When you do if(<expression>), it evaluates <expression>, then converts it to a boolean.
In the docs, it says:
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).
So, when you do if(!$email), it converts $email to a boolean following the above rules, then inverts that boolean.

Related

if statement and functions

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

PHP if (variable)

In various PHP tutorials I see this syntax -
if ($_POST) {
do something
}
I want to know whether this is equivalent to either isset or !(empty) (either one) or has different properties.
It attempts to evaluate the expression and cast it to boolean.
See 'Converting to boolean' at http://php.net/manual/en/language.types.boolean.php to see which values will be equivalent to true and which to false.
It does NOT however check for array key existence (i.e. isset), so if you try if ($_GET['somekey']) but somekey does not exist, you will see PHP Notice: Undefined index: somekey and then false will be assumed.
The best practice would be to perform empty() or isset() checks manually first as fits.
Good question. You are adressing one of PHPs dark sides if you ask me.
The if statement
Like in any other language I can imagine if evaluates the parameter to either true or false.
Since PHP doesn't really know types you could put any expression as parameter which will then be casted to bool as a whole
Following values are considered to be "FALSE"
boolean FALSE
integer 0
float 0.0
empty string
string "0"
any array with zero elements
NULL e.g. unset variables or $var = null
SimpleXML objects when created from empty tags
EVERY other value or expression result is casted to bool TRUE
Now, knowing this, all we need to find out is, what an expression or function returns when executed
If no POST data is set, the following expression would be TRUE
$_POST == FALSE
The isset function
isset returns bool TRUE when the given variable is set and not null.
parameters can be variables, array elements, string offsets and data members of objects.
In PHP 5.4 they fixed the behaviour with string offsets
$var = FALSE;
isset( $var ) === TRUE;
$var === FALSE;
More here
http://de1.php.net/manual/en/function.isset.php
The empty function
Returns false when a variable is considered to be empty or does not exist.
Those values are considered empty:
Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
The following values are considered to be empty:
"" (empty string)
0 (integer)
0.0 (float)
"0" (string)
NULL
FALSE
array() (empty array)
Also declared variables without value are empty
compare table
$var = FALSE;
isset($var) === TRUE;
empty($var) === TRUE;
$var === FALSE;
if ($_POST)
This will evaluate to true if there are any elements in the POST array.
if(isset($_POST))
This will always evaluate to true because the POST array is always set, but may or may not contain elements, therefore it is not equivalent to the first example.
if(!empty($_POST))
This however, is equivalent to the first example because empty() checks for contents in the array.
A good generic way of testing if the page was posted to is:
if($_SERVER['REQUEST_METHOD'] == 'POST')
$_POST:
this is used to find whether data is passed on using HTTP POST method and also extracting the variables sent through the same which are collected in an associative array
isset:
checks whether a variable is set(defined) or is NULL(undefined)
PHP.net is an invaluable source of information for figuring out the intricacies and quirks of the language.
With that said, those are not equivalent. The if statement converts the expression to a boolean value (see here for information on what is considered false).
isset is used to "determine if a variable is set and is not NULL."
empty determines whether a variable is empty, i.e., "it does not exist or if its value equals FALSE."
Best practice if you want to check the value of a variable but you aren't sure whether it is set is to do the the following:
if(isset($var) && $var) { ... }
ie check isset() AND then check the variable value itself.
The reason for this is that if you just check the variable itself, as per the example in your question, PHP will throw a warning if the variable is not set. A warning message is not a fatal error, and the message text can be suppressed, but it's generally best practice to write code in such a way that it doesn't throw any warnings.
Calling isset() will only tell you whether a variable is set; it won't tell you anything about the value of the variable, so you can't rely on it alone.
Hope that helps.

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).

Is There A Difference Between strlen()==0 and empty()?

I was looking at some form validation code someone else had written and I saw this:
strlen() == 0
When testing to see if a form variable is empty I use the empty() function. Is one way better than the other? Are they functionally equivalent?
There are a couple cases where they will have different behaviour:
empty('0'); // returns true,
strlen('0'); // returns 1.
empty(array()); // returns true,
strlen(array()); // returns null with a Warning in PHP>=5.3 OR 5 with a Notice in PHP<5.3.
empty(0); // returns true,
strlen(0); // returns 1.
strlen is to get the number of characters in a string while empty is used to test if a variable is empty
Meaning of empty:
empty("") //is empty for string
empty(0) // is empty for numeric types
empty(null) //is empty
empty(false) //is empty for boolean
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)
strlen() simply check if the the string len is 0. It does not check for int, float etc. What is your situation.
reference
empty() will return true if $x = "0". So there is a difference.
http://docs.php.net/manual/en/types.comparisons.php
$f = 0; echo empty($f)? 'Empty':'Full'; // empty
$f = 0; echo strlen($f); // 1
For forms I use isset. It's more explicit. ;-)
empty is the opposite of boolean false.
empty is a language construct.
strlen is a function.
strlen returns the length of bytes of a string.
strlen($str)==0 is a comparison of the byte-length being 0 (loose comparison).
That comparison will result to true in case the string is empty - as would the expression of empty($str) do in case of an empty (zero-length) string, too.
However for everything else:
empty is the opposite of boolean false.
strlen returns the length of bytes of a string.
They don't share much with each other.
The strlen way is almost perfect if you want to check if something is "empty as string", that is, when a single zero should NOT be counted as nothing but empty strings, empty arrays, null and false should all be considered no value. This is quite frequently needed.
So my recommendation would be:
count($x)*strlen("$x")
This gives you:
0 for false
0 for null
0 for "" (empty string)
0 for [ ] (empty array), no warning
1 for a numeric zero
1 for "0" (a string zero)
Surely you can do empty($x) && "$x"!=="0" - it's more to the point but a little noisier, and surprisingly their time cost is nearly equal (under 50ms for a million iterations) so no reason to choose one over the other. Also, if you add !! (boolean cast) before strlen, you'll get a clear 0/1 answer for the question and sometimes it can be more convenient than true/false (debugging situations, switch, etc).
Also note that objects can't be checked like this. If there's a chance that an object comes along, go for the empty()-method. Objects are stubborn creatures.
empty() is for all variables types. strlen(), I think, is better to use with strings or something that can be safely casted to strings. For examle,
strlen(array());
will throw PHP Warning: strlen() expects parameter 1 to be string, array given error
when the input is 0,
strlen(0) = 1
empty(0) = false <-- non-empty

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