Question Regarding Variable State in IF Statement - php

I am a dead beginner with PHP and have been reading through 'PHP for the Web: Visual Quickstart Guide 4th Ed.' by Larry Ullman and have a question regarding something I came across in the book.
At the end of each chapter he has a few questions for review and I am stuck on one of them and not sure if I have the correct answer or the correct train of though regarding it.
The question is as follows:
Without knowing anything about $var will the following conditional be TRUE or FALSE? Why?
if ($var = 'donut') {...
I am apt to say that it will be false because we don't know if $var has been assigned the value donut yet within the program but I am not sure.
Can anyone help explain this to me so I can grasp this concept and feel confident about it?

There is only one equal sign so it will return true. Heres why: It is assigning "donut" to $var which makes $var true. :)
If the statement had 2 or 3 equal signs we wouldn't know what it would return.

It will be true since the $var variable is define to be 'donut', if the $var variable is empty then it should be returning false.
Example
$var = ''; // False
$var = 'something something'; //True

This conditional will always evaluate to TRUE because the value donut is assigned, and then the value of $var is returned to the if() statement. The assignment happens first.
A successful assignment to a variable causes that variable to be returned immediately. A non-empty string is a "truthy" value, and is returned as such.
If instead it was assigned as:
if ($var = "") {}
It would evaluate to FALSE, according to PHP's boolean evaluation rules:
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)
Addendum
Just to add, as a practical example of assignment inside a flow control conditional you probably see almost every day -- the while() loop we typically use to retrieve a rowset from a MySQL result resource:
while ($row = mysql_fetch_assoc($result)) {
// executes this inner block as long as $row doesn't
// recieve a FALSE assignment from mysql_fetch_assoc()
// reaching the end of its rowset
}

it will be true as $var = 'donut' is an assignment and not 'is equals to (==)'. The = operator assigns the value of the right hand side to the variable on the left hand side.The == operator checks whether the right hand side is equal to the left hand side.

To make things simpler here is a better explanation.
<?php
// To assign a value to a variable you do this
$var = 'donut';
// To evalute the value of a variable you do this.
if($var == 'donut') { }
// Notice the existence of double equals here.
// If you have code like this:
$var = 'donut holes';
if ($var = 'donut') {
// This is true because any value you assign with ONE equals is always TRUE
print $var; // Will output 'donut' because you reassigned it.
}

Related

What is the actual function difference as to its application on a code, between if(isset) and !empty()....based on my code here? [duplicate]

Could you help me to improve my coding style?:) In some tasks I need to check - is variable empty or contains something. To solve this task, I usually do the following.
Check - is this variable set or not? If it's set - I check - it's empty or not?
<?php
$var = '23';
if (isset($var)&&!empty($var)){
echo 'not empty';
}else{
echo 'is not set or empty';
}
?>
And I have a question - should I use isset() before empty() - is it necessary? TIA!
It depends what you are looking for, if you are just looking to see if it is empty just use empty as it checks whether it is set as well, if you want to know whether something is set or not use isset.
Empty checks if the variable is set and if it is it checks it for null, "", 0, etc
Isset just checks if is it set, it could be anything not null
With empty, the following things are considered 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)
From http://php.net/manual/en/function.empty.php
As mentioned in the comments the lack of warning is also important with empty()
PHP Manual says
empty() is the opposite of (boolean) var, except that no warning is
generated when the variable is not set.
Regarding isset
PHP Manual says
isset() will return FALSE if testing a variable that has been set to NULL
Your code would be fine as:
<?php
$var = '23';
if (!empty($var)){
echo 'not empty';
}else{
echo 'is not set or empty';
}
?>
For example:
$var = "";
if(empty($var)) // true because "" is considered empty
{...}
if(isset($var)) //true because var is set
{...}
if(empty($otherVar)) //true because $otherVar is null
{...}
if(isset($otherVar)) //false because $otherVar is not set
{...}
In your particular case: if ($var).
You need to use isset if you don't know whether the variable exists or not. Since you declared it on the very first line though, you know it exists, hence you don't need to, nay, should not use isset.
The same goes for empty, only that empty also combines a check for the truthiness of the value. empty is equivalent to !isset($var) || !$var and !empty is equivalent to isset($var) && $var, or isset($var) && $var == true.
If you only want to test a variable that should exist for truthiness, if ($var) is perfectly adequate and to the point.
You can just use empty() - as seen in the documentation, it will return false if the variable has no value.
An example on that same page:
<?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';
}
?>
You can use isset if you just want to know if it is not NULL. Otherwise it seems empty() is just fine to use alone.
Here are the outputs of isset() and empty() for the 4 possibilities: undeclared, null, false and true.
$a=null;
$b=false;
$c=true;
var_dump(array(isset($z1),isset($a),isset($b),isset($c)),true); //$z1 previously undeclared
var_dump(array(empty($z2),empty($a),empty($b),empty($c)),true); //$z2 previously undeclared
//array(4) { [0]=> bool(false) [1]=> bool(false) [2]=> bool(true) [3]=> bool(true) }
//array(4) { [0]=> bool(true) [1]=> bool(true) [2]=> bool(true) [3]=> bool(false) }
You'll notice that all the 'isset' results are opposite of the 'empty' results except for case $b=false. All the values (except null which isn't a value but a non-value) that evaluate to false will return true when tested for by isset and false when tested by 'empty'.
So use isset() when you're concerned about the existence of a variable. And use empty when you're testing for true or false. If the actual type of emptiness matters, use is_null and ===0, ===false, ===''.
Empty returns true if the var is not set. But isset returns true even if the var is not empty.
$var = 'abcdef';
if(isset($var))
{
if (strlen($var) > 0);
{
//do something, string length greater than zero
}
else
{
//do something else, string length 0 or less
}
}
This is a simple example. Hope it helps.
edit: added isset in the event a variable isn't defined like above, it would cause an error, checking to see if its first set at the least will help remove some headache down the road.

PHP - Which conditional test to use?

Are those 2 expressions equivalent (I mean "can I replace the 1st one with the 2nd one):
if ($var) { ... }
and
if (!empty($var)) { ... }
I feel there is a difference but I rationally cannot say which one.
For me the first one evaluates if $var is true or false and I may be wrong but "false" evaluations means that $var is false (boolean), empty (string, object or array), 0 value (int, float or string) or undefined ... that's the way the "empty" function works (http://php.net/manual/en/function.empty.php).
If those tests are equivalent (at least in specific cases), which is better to use (readability, performance, maintenance, ...)?
Thanks
They differ in that for your second example, $var doesn't have to be set before using it. In the first case, if $var isn't set, a notice will be generated, while in the second example, it won't.
This can be useful for values submitted by users inside the $_GET and $_POST superglobals (.. and for $_COOKIE and $_SERVER).
// will generate a notice if there is no `foo` in the query string
if ($_GET['foo'])
// will not generate a notice, even if the key is not set
if (!empty($_GET['foo']))
!empty($var)
Determine whether a variable is considered to be not empty. A variable is considered not empty if it does exist or if its value equals TRUE. empty() does not generate a warning if the variable does not exist.
if ($var) { ... }
You'll test if $var contains a value that's not false -- 1 is true, 123 is too
Extra:
isset($var)
Using isset(), you'll test if a variable has been set -- i.e. if any not-null value has been written to it.
-
It all depends on what you want to check/test. I do hope it helps.
empty() -> If variable not exist or its equals to false empty function returns true.
Imagine that you did not declare $var
if ($var) {
echo '1';
}
else {
echo '2';
}
Output will be:
NOTICE Undefined variable: var on line number *
If you use empty:
if (!empty($var)) {
echo 1;
}
else {
echo 2;
}
Output will be:
2
Also the following values are considered to be empty
$var = 0;
$var = "";
$var = false;
$var = null;
Also check isset() function Php.net isset

PHP - simple condition with parenthesis

I have a stupid question about this condition.
Why when I put parenthesis, the result of the condition changes?
$std = new \stdClass();
$std->bool = false;
$resultCond1 = isset($std->bool) and $std->bool == true;
$resultCond2 = (isset($std->bool) and $std->bool == true);
var_dump($resultCond1); // True.
var_dump($resultCond2); // False.
I believe this is due to operator precedence.
Notice in that table that the assignment operators lie firmly between and and &&. Here's what I think is happening:
In the first example, isset is returning true and, prior to the and operation taking place the assignment is happening. After the assignment, the result of the assignment is and'ed and the result of that and operation is then summarily discarded.
In the second example the parentheses dictate that the assignment happens last and so you get the expected result.
You can see this more clearly if you remove the assignment operation altogether and just dump the result of the operations themselves:
var_dump(isset($std->bool) and $std->bool == true); // bool(false)
var_dump((isset($std->bool) and $std->bool == true)); // bool(false)
Both of these conditions are not outputting same result because of operator precedence.
1) For the first one - isset($std->bool) returns true, after that it will check and $std->bool, lastly it will compare that result with true
2) For the second one - it will check isset($std->bool) and $std->bool == true separately. Then compare both of these result.
Second one is more convenient & cleaner way to accomplish this type of work.

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

A php if statement with one equal sign...? What does this mean?

I'm attempting to troubleshoot a problem, and need to understand what this if statement is saying:
if ($confirmation = $payment_modules->confirmation()) {
All the resources I can find only show if statements with double equal signs, not single. Is this one of the shorthand forms of a php if? What is it doing?
(If it's actually wrong syntax, changing it to a double equal sign doesn't resolve the problem. As-is, in some scenarios it does return true. In the scenario I'm troubleshooting, it doesn't return true until after I refresh the browser.)
Any help is greatly appreciated!!!
It's a form of shorthand, which is exactly equivalent to this:
$confirmation = $payment_modules->confirmation();
if ($confirmation) {
}
This will first assign the value of $payment_modules->confirmation() to $confirmation. The = operator will evaluate to the new value of $confirmation.
This has the same effect as writing:
$confirmation = $payment_modules->confirmation();
if ($confirmation) {
// this will get executed if $confirmation is not false, null, or zero
}
The code works because an assignment returns the value assigned, so if $payment_modules->confirmation() is true, $confirmation will be set to true, and then the assignment will return true. Same thing for false.
That's why you can use a command to assign to many variables, as in a = b = 0. Assigns zero to b and returns that zero. Therefore, it becomes a = 0. And a receives zero and it will return that zero, which can or can not be used.
Sometimes people like to do an assignment and then check if the assignment went through okay. Pair this up with functions that return false (or equivalent) on failure, and you can do an assignment and a check at the same time.
In order to understand this, remember that assignments are a kind of expression, and so (like all expressions) have a return value. That return value is equal to whatever got put into the variable. That is why you can do something like
a = b = c = 0;
to assign all of those variables at the same time.
= means assignment ( $a = 1 ), == is for comparison ( true == false is false ). I think in your example it should use = because it assigns it to the return value of confirmation, which should be something that evaluates to true.
Try doing a var_dump:
var_dump( $payment_modules->confirmation() );
See what boolean it evaluates to, and from there you can troubleshoot. Post more code if you want more help.
class test() {
public function confirmation() { return true; }
}
$boolean = test::confirmation();
var_dump( $boolean );
Will equate to true

Categories