I am having a bit of trouble wrapping my head around this, so I thought I will ask it..
I have this code:
$x="string";
var_dump($x==0); //says true
var_dump($x==true); //says true
var_dump(true==0); //says false
What I understand is:
In 1, `string` gets converted to number, which becomes `0` so condition is true
In 2, `string` is a value, so condition is true
In 3, `true` is not equal to `0` so condition is false
Individually they all make sense, but in a sequence they just don't! I have heard many people say it is because the conditional operator in PHP is not transient. Can someone explain what that means, and how to make sense of this?
Why in the world wouldn't that make sense? You never change the value of x, so those statements are dependent on the original value of x which is "string".
You are assuming x is changed to 0 in the first var_dump but it is not. It is merely compared to 0/false. This statement would perform the variable change that you think is happening:
var_dump(($x = 0) == 0);
Or:
var_dump(($x = false) == 0);
Related
I want to try and make my code as efficient as possible and from what ive read
if($process == true)
Will process faster than something that calls a function. I.e
if(count($total) == 100)
So if i had an OR inside my if and the first condition was a simple boolean check and it turned out to be true would the second part of the condition still be checked anyway?
For example
$process = true;
if($process == true || count($total) == 100)
Would the count function still be called even though process is true and that is enough the make the condition pass.
PHP has indeed a mechanic named short-circuit:
http://php.net/manual/en/language.operators.logical.php#example-140
If the first operand of a logical OR is true, then the second part isn't evaluated, and the function isn't called.
Since comparing a variable to a boolean is faster than calling a function in PHP, this mechanic can help you to optimize, but never forget that premature optimisation is the root of all evil.
It will work same as exactly logical operator works. For example foo() will never get called.
if (false && foo()) {
}
if (true || foo()) {
}
In case of OR once it found a true statement it wont check further conditions,
In case of AND once it found a false statement it wont check further conditions.
its known as lazy evaluation.
illustration:
<?php
$var=0;
if($var++ || $var++){//Since 0 means false in Php both conditions will be checked
//Do nothing
}
echo $var;//output :2
if we change condition to if(++$var || $var++) the first condition will return true hence next condition will not be checked thus it will print output as 1;
If any statement inside a or is true other statements will not be checked and the if will be evaluated to true.
If you are checking a and statement all statements needs to evaluate to true and if any of them is false the stamen check will stop because the if is already false.
Just another important detail is that a function inside a if does not slow down the if check, what will slow down is what the function is doing and if it needs a lot of processing of course will be slower than just check a boolean but do not get afraid of use functions because they are very important in any system.
(I remember this from C# but I'm quite sure it's the same in php)
This depends if you use the single | or double || I think if you used the single ones it would still go do the other one ( usefull for when theres a function like loggin behind it ) if you use double and the first one is true it'll skip the second condition.
(This could be the other way around, so best bet is to try it using Javascript eg. create 2 function each returning true after alerting something, and thest these with either 1 line or 2)
I have a terrible confession. I've been using variations of the below for ages.
for($x=0;10>$x;++$x){
echo '<li style="color:#'.(($c=!$c)? "fff":"eee").'">example $x</li>";
}
My dilemma is that I don't entirely understand how it works. I know that $c=!$c makes the ternary conditional alternate, but I don't understand how. Googling "php =!" and the likes yields nothing helpful (no surprise given the query).
!= is an operator, but this uses =!
Is this a ternary conditional declaration? If so, how does this one work? I understand the general conditional declarations, but not this one... assuming it even is one.
Any answer or link to documentation would be greatly appreciated.
They are two separate operators. You should read it as
$c = !$c;
In other words, assign the result of the expression !$c back to the variable $c. So indeed, it toggles the value of $c.
Additionally, an assignment like this also returns the assigned value, so you can evaluate it immediately. So in words, the expression ($c=!$c)? "fff":"eee" says:
"Invert the value of $c. If the new value is true, return 'fff', otherwise return 'eee'."
It's not an operator, it just needs better spacing:
$x = !$x;
it's just inverting the value.
=! is not an operator. It is two: = means assignment, and ! means negation.
If $c is true, then !$c is false (and vice versa).
And assignments evaluate to their new value.
You're setting $c to be not itself. So if $c == true you are saying $c = not true, I.e. false which will also count as false for the ternary.
Next iteration you set $c = not false I.e. true and so on.
I have this code
if (true == $run_user['online'] {
$result = 'Online now!';
} else {
$date = $run_user['lastloggedin'];
$result = Agotime($date);
}
$run_user is to check the database by the way
So whenever I change the value in the database to false, it will still just result "Online Now!" Instead of saying what it's supposed to say, which is for example 1 hour ago.
#John Conde had it right, but I can expound on what is actually happening.
In PHP there are certain things that will be left for interpretation. Boolean checks are one of those things. Here is a couple lists of things that will be interpreted in a Boolean check:
These will be interpreted as TRUE
Boolean true, of course
Non-empty strings
Any non-zero integer
A function, object or array
These will be interpreted as FALSE
Boolean false
The integer 0
An empty string
null
The not (!) character followed by an interpreted true or Boolean true
These might be confusing at times, but the best thing to do for checking is to make sure you know what type of variables you are passing into the conditional. Sometimes it may be useful to use a strict comparator like so:
if(true === $variable){ ... }
The third equal sign will tell PHP to only interpret this as true/false if it is EXACTLY what I am comparing it to. So $variable = true; would work, but $variable = 1; would not. Without the strict comparator, both versions would work. This issue comes into play a lot when you are working with integers where 0 needs to be interpreted as true and null should be false.
the code I'm looking at does this...
while ($info=mysql_fetch_array($data_jurisdiction))
{
//some stuff
}
I'm wondering what does this while statement do? it has an assignment operator within it, so as long as $info gets assigned a value other than false, this code will execute?
[... S]o as long as $info gets assigned a value other than false, this code will execute?
Quite, yes. Even there is an assignment operator within that expression, the expression itself still stands for a value. In this case the result of the whole expression is equal to the assignment to $info. In other words: The expression is the same as $info or the expression has been assigned to $info - the last variant is perhaps the best description.
So now whenever $info equals to true, the code block inside while will be executed.
Keep in mind that the comparison is a loose comparison. So not only false but as well NULL or an empty array will stop the execution of the inner code-block.
For each record $info will be populated with the current row, until it reaches the end of the result set when it will be set to false (which should stop the while loop).
great answer from hakre. what is said is that
while ($info=mysql_fetch_array($data_jurisdiction))
will execute in the same way as this
while (mysql_fetch_array($data_jurisdiction)==true)
or even this
$info = mysql_fetch_array($data_jurisdiction);
if($info==true)
so keep in mind that if mysql_fetch_array($data_jurisdiction) returns anything that can be evaluated to false, the assignment won't work. some of those values are (and I know I will forget a few:
0
"0"
false
"false"
NULL
""
array() (not fully sure about this one)
as long as $info gets assigned a value other than false, this code will execute?
Yes.
it does loop and stops if $info is false
mysql_fetch_array(); clears row by row so there is new result alltimes
A while loop will execute the nested statement(s) repeatedly, as long as the while expression evaluates to true.
The expression in your example $info = mysql_fetch_object($data_jurisdiction) checks whether the $info, the assigned value from mysql_fetch_object() is equal to true, after type juggling.
It is important to understand two things here:
mysql_fetch_object() returns the next row of the result set until the end of the data set is reached, where it returns false. See the method documentation here.
All assigned values of variables which are not equal to 0, or null evaluate to true after type juggling.
From the manual:
The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3.
Also from the manual about mysql_fetch_array:
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
Therefore, once there are no more rows, the assignment will turn into:
$info = false
Which will get evaluated as false in the while condition, causing the loop to terminate.
I was studying some code I found on the web recently, and came across this php syntax:
<?php $framecharset && $frame['charset'] = $framecharset; ?>
Can someone explain what is going on in this line of code?
What variable(s) are being assigned what value(s), and what is the purpose of the && operator, in that location of the statement?
Thanks!
Pat
Ah, I just wrote a blog post about this idiom in javascript:
http://www.mcphersonindustries.com/
Basically it's testing to see that $framecharset exists, and then tries to assign it to $frame['charset'] if it is non-null.
The way it works is that interpreters are lazy. Both sides of an && statement need to be true to continue. When it encounters a false value followed by &&, it stops. It doesn't continue evaluating (so in this case the assignment won't occur if $framecharset is false or null).
Some people will even put the more "expensive" half of a boolean expression after the &&, so that if the first condition isn't true, then the expensive bit won't ever be processed. It's arguable how much this actually might save, but it uses the same principle.
&& in PHP is short-circuited, which means the RHS will not be evaluated if the LHS evaluates to be false, because the result will always be false.
Your code:
$framecharset && $frame['charset'] = $framecharset;
is equivalent to :
if($framecharset) {
$frame['charset'] = $framecharset;
}
Which assigns the value of $framecharset as value to the array key charset only if the value evaluates to be true and in PHP
All strings are true except for two: a string containing nothing at all and a string containing only the character 0