I am new to PHP and am currently constructing a do/while loop from a tutorial. I would understand if the whole condition was ($variable == true) or ($variable == false), however in the tutorial the while condition is simply while($variable). Could anyone explain this to me?
Here is the tutorial code.
<?php
$loopCond = false;
do {
echo "<p>The loop ran even though the loop condition is false.</p>";
} while ($loopCond);
echo "<p>Now the loop is done running.</p>";
?>
All such conditional statements, including while and if, are evaluating the given expression against true. If the expression results in true, the statement executes the action. If it results in false, it won't.
$var == true is an expression which compares $var to true. The result of this expression is either true or false. The important point to understand here is expressions. Expressions are things which return values. Try var_dump($var == true) or var_dump(4 > 6). It shows you that the expressions return a boolean value. Here:
if ($var == true)
first $var is compared to true, which yields either the value true or false, which is then evaluated by if whether it's true or false, which then prompts if to execute the following statement or not.
In other words: it's redundant.
if ($var)
This simply causes if to evaluate whether $var is true or false and then execute the following statement. The == true is essentially already "built in".
The following statements are all essentially equivalent:
if ($var)
if ($var == true)
if (($var == true) == true)
if ((($var == true)) == true) == true)
...
A boolean value true or false should not be used with a redundant $c == true as the result is the same as $c: true or false
$driving = true;
while ($driving) {
while ($driving == true) { // ugly
while (! $driving) { // while not driving.
while ($driving == false) { // ugly
$drinking = ! $driving;
if ($driving && $drinking) {
Hence also use adjectives for boolean variables.
A condition is met, if the value or statement in it is considered as true.
The code $variable == true is a statement that looks whether the value of the variable is true and if it is, yields true - Or false if it is not.
However, as this means, that $variable itself can only ultimately be true or false, you don't even need the statement, as its return value will also be one of those two.
Therefore $variable is exactly the same as $variable == true.
I hope this made it clear.
The semantic of while/do-while is
while(<boolean expression>) {
// do your stuff
}
A boolean expression is anything that evaluates to true or false. So, if $loopCount is true, then $loopCount == true is checked on every loop and evalutes to true. But you could also write $LoopCount as condition, since it also evaluates to true.
This is very handy for using other data types, e.g. integers.
$count = 0;
while ($count < 10) {
$count = $count +1;
}
Here $count < 10 is a boolean expression that evaluates to true as long as $count is not higher then 9.
A while loop runs as long as the condition is met, in other words, as long as the boolean expression you provide evaluates to true.
You can also just use a variable, e.g. $loopCount when that variable evaluates to a boolean or a constant (even the constant value true).
Like Padarom said: Therefore $variable is exactly the same as $variable == true.
In your case: The while-do loop determines if redo the loop-body after the first run. Means the loop-body is executed exactly one time regardless what value $variable has. After the first run, the while($variable) checks if the expression is true. If so, the loop-body is executed second time and so forth.
Check PHP reference for do-while loops here. PHP.net do-while reference
while ($loopCond) and while ($loopCond == true) is the same thing. It checks the "trueness" of whatever you put in the brackets.
If I ask a question "does sun set in the west ? " what would be your answer, definitely YES OR TRUE. Same as compiler always look for statement value. Take a look
$condition = true;
if($condition == true )
// above will return TRUE; in short $condition == true will replaced by true at runtime. But if we place true directly which is $condition value or can say we place $condition instead true thus statement become shorten and look like...
if($condition) {
}
Related
I have some code from a previous programmer and I'm a little confused to what it means.
The if statement is:
if( !$this->report = $this->get_report()){
... do something }
I'm used to seeing the if statement with some "truthy" condition or a comparison operator.
Is this saying if $this->report is false or doesn't exist then make it = $this_.get_report()?
if( !$this->report = $this->get_report())
This line is doing two things:
assigning the value of $this->get_report() to $this->report
validating whether the value loosely compares to false
Only if it does compare (loosely to false), it runs the block do something
Example of another loose comparison:
<?php
if(!$foo = null) {
// going to process this block
}
$foo is assigned a null value
null loosely compares to false in PHP
null == false loose comparison
null !== false strict comparison
!false results in true, so the block gets executed
I found an example php assignment statement online which maybe resembles a tertary conditional condensed statement, but not quite. Does anyone have insight as to how to read this assignment statement?
$access = $access || $note->uid == $user->uid && user_access('note resource view own notes');
My first guess was "assign to access whatever is in access, or if empty, whether uid values are equal and'd with the return of user_access." But I get the feeling that is not correct, as it seems illogical.
First have a look at the Operator Precedence
== comes before && comes before || comes before =
Thus your statement is more clear with adding the following parentheses:
$access = (
$access
||
(
($note->uid == $user->uid)
&&
user_access('note')
)
);
assign to access whatever is in access, or if empty,
Not quite: assign to $access the value true* when $access already evaluates to true (true, 1, "some string" etc), or
whether uid values are equal and'd with the return of user_access
Correct
And otherwise assign false. After this statement $access is always either true or false, even when $access === 'yes' before.
Note*: || and && are boolean operators, only capable of 'returning' true or false
I had this exact type of statement in a library way back, and it's basically an elaborate (or maybe just badly-styled?) null-check. Because PHP uses short circuit evaluation, the right-hand side of the or-expression will not evaluate if the left hand one was null.
I have noticed that PHP doesn't run the second or other parameters of 'if statement' if the first parameter true.
if($this->sessions->remove("registered_id") or $this->sessions->remove("user_id")){
echo "you have logged out";
}else {
echo "wth?";
}
This how I use the if. Also here is the remove function from sessions class.
public function remove($key){
if(isset($_SESSION[$key])){
unset($_SESSION[$key]);
return true;
}
else
{
return false;
}
}
The thing that I want to do is run both of this parameters.. I hope I can tell the problem..
You need to execute both functions, store their respective results, then test on these results.
$resultA = $this->sessions->remove("registered_id");
$resultB = $this->sessions->remove("user_id");
if ($resultA or $resultB)
{
…
It's by design that the second statement is not executed, because its result will be irrelevant.
If by other parameters you mean the second condition, then use an AND instead of OR
If by other parameters you mean the else, then use a separate if statement instead.
edit
If you're trying to execute both statements, use bitwise operators, check out this manual:
http://www.php.net/manual/en/language.operators.bitwise.php
Something like:
if(a | b){
}
That will execute both a and b, but still is an 'or' comparison.
That result is to be expected. This is what logical operators do.
You would need to use && or and to achieve what you seem to be looking for:
if ($this->sessions->remove("registered_id") && $this->sessions->remove("user_id")) {
Here is why:
The && or and keyword means that all evaluations must return true. So:
if ($a && $b) {
// $a and $b must both be true
// if $a is false, the value of $b is not even checked
}
The || or or keyword means that either evaluation must return true. So:
if ($a || $b) {
// Either $a or $b must be true
// If $a is false, the parser continues to see if $b might still be true
// If $a is true, $b is not evaluated, as our check is already satisfied
}
So in your case, if the $this->sessions->remove("registered_id") successfully did it's thing, the $this->sessions->remove("user_id") is never called, as our check is already satisfied with the outcome of the first call.
I am using CodeIgniter.
I set $config['global_xss_filtering'] = FALSE in a config file.
Then I find this code in system/core/Input.php:
$this->_enable_xss= (config_item('global_xss_filtering') === TRUE);
What actually this code it doing? It doesn't look like a ternary statement. It seems to me is
$this->_enable_xss= (FALSE === TRUE);
In this case $this->_enable_xss returns FALSE?
This expands out to:
// If global_xss_filtering is a boolean TRUE (by strict comparison)
if (config_item('global_xss_filtering') === TRUE) {
// Set _enable_xss to TRUE
$this->_enable_xss = TRUE;
}
// Otherwise set it FALSE
else $this->_enable_xss = FALSE;
The part in () (config_item('global_xss_filtering') === TRUE) is a boolean comparison which will return TRUE or FALSE. That value is stored in $this->_enable_xss.
So in your case, you are correct that you're evaluating
$this->_enable_xss= (FALSE === TRUE);
... which sets $this->_enable_xss to FALSE.
each comparison operator returns a boolean.
Yours checks if you got true left and right.
So, yes, var_dump(true === false);//bool(false)
is there more code around the statement? I would say your assessment is valid. Looking at this forum http://codeigniter.com/forums/viewthread/160281/#771216 it looks like it's just setting the _enable_xss based on the config value so you can control the setting. Why they need to do a comparison is beyond me, seems unnecessary.
So my code in the past needed a variable to run through 2 functions and then return the value as such.
function 1($variable) {
check($variable);
return $variable // either a -1, -2 or true;
}
// pass the return to next function
function 2($variable) {
check($variable);
return $variable // either a -1, -2 or true;
}
On the next check it returns a message to the user as such:
if($variable == -1) // display message
if($variable == -2) // display message
if($variable == true) // display message
Now, per requirement of work the variable must go through a 3rd function check still returning a -1, -2 or true and then go onto the final if statements for display.
Now this is where it gets odd. If I keep it at 2 functions the if statements work, however if I run it through the 3rd check function I need to format my if's like this in order to correctly check the return:
if($variable === -1) // display message
if($variable === -2) // display message
if($variable === true) // display message
Notice I have to add the 3rd '=' symbol. I just can't figure out why this is happening. Is this normal by some PHP law I don't know about or is this a bug?
This is not odd behavior, it's very natural for PHP.
Following expression:
if ($variable == true) {
}
means that PHP will cast left operand to less pretensive type(in this case BOOLEAN) and do comparison after this. Which obviously will result in TRUE if $variable value is not 0 or FALSE or NULL or ''
In second case i.e. === there is strict check value and type of both operands are compared.
The triple equals sign (===) only returns true if the two objects being compared are identical (of the same type and value), not just equal.
For example:
$a = 1;
$b = "1";
echo $a == $b; // True
echo $a === $b; // False
Your code does not show how you call the functions and store returns, there may be a problem. Plus, I suppose you called function 1 and 2 only for illustration because as you know you cant start name of the function with a number.
=== is 'equals exactly' (value and type). Often used for logical tests, because sometimes you need to distinguish 0 from false and 1 from true.