Basically I have the following code:
However when I var_dump $isLoggedIn and $isset($_COOKIE['access_token']) both are false (so through the ! in the <?php?> it gets true) and the href should be connect.php... but it always is main.php?auto=true".autoooooo does not even exist (I just made it for testing) and href should actually be empty.
What am I doing wrong?
In php, the ternary operator (?:) associates left-to-right (unlike in C or perl where it associates right-to-left).
That means that it evaluates the first test ? value 1 : value 2, and then uses that result to determine which value of the second operator to use.
Your construct would work in C or perl, but in php, you need to add brackets around each subsequent ternary operator.
Also, for readability, I recommend you add quite a few newlines and indents in your code.
Use brackets for your 2nd clause:
$b1 = false;
$b2 = false;
echo $b1 ? 'b1 true' : ($b2 ? 'b2 true' : 'all false') ;
Output:
all false
Related
I have an array ...
$a= array(1,2,3,4);
if (expr)
{ echo "if";
}
else
{ echo 'else';
}
When expr is ( $a = '' || $a == 'false') , output is "if" ,
but when expr is ( $a == 'false' || $a = '' ) , output is "else"
Can anyone explain why & how ordering makes a difference ??
Edit : I understand that I am assigning '' to $a. That is not the problem. The real question is : What does the expression $a = '' return? And why does reversing the order of the 2 situations switch us from the IF section to the ELSE section?
AGAIN : I UNDERSTAND I AM ASSIGNING NOT COMPARING. PLEASE ANSWER THE QUESTION AS IS.
First, never use = as a comparison operator. It is an assignment operator.
The difference is that false (as a boolean) is not the same as 'false' as a string.
Certain expressions are type juggled by PHP to evaluate somewhat differently to how you would expect.
false==""
// TRUE.
false=="false"
// FALSE.
Additionally, when you try to compare numbers to strings, PHP will try to juggle the data so that a comparison will be performed. There is a lot to it (much more than I will post here) but you would do well to investigate type juggling and various operators. The docs are a great start for this. You should also have a read of the comparison operators which go into a lot of detail about how various comparisons will work (depending on whether you use == or === for example).
With $a = '' you are setting $a to an empty string. This is the same as:
$a = '';
if($a){
echo 'if';
}
The || operator checks if the first condition is true and if it is, it continues with the code in the brackets. In PHP, if $a is set to anything, it will return true. In the second case $a does not equal the string 'false' (you are not comparing it to a boolean false even!), so it executes the code in the else part.
And Fluffeh is not entirely correct. You can use the assignment operator in an if condition very effectively, you just have to be smart about it.
$a = '' is an assignment: you have, in error, used = in place of ==. Assignment is an expression which has the value of the thing your assigning.
A single equals sign = is the assignment opporator, so $a = '' is assigning an empty string to $a not checking if it is equal to.
In your 1st example you set the value of $a to an empty string, then check if it is false. An empty tring evalutes to false in php, so the conditional is true.
In your second example, you check if $a equals false 1st (when the value of $a is an array), so the conditional is false
I can't understand what is wrong I am doing with this if else shorthand code
$item = '<li '. ($avatar_size > 50) ? .'style="overflow:hidden">';
I only want to check if condition true than add inline style else nothing.
Edit:
Of course in above statement it will remove > too when condition is false so I tried other statement but none of working. I am sure I must doing stupid mistake but can't figure it out.
$item = '<li '. ($avatar_size > 50) ? .'style="overflow:hidden"'.:. '' .'>';
There is no "shorthand if", ?: is an operator and it always must consist of ? and :. The best you can do with this is:
$item = '<li' . ($avatar_size > 50 ? ' style="overflow:hidden"' : null) . '>';
I have a late answer with more explanation, although the initial one is right.
About the ternary operator
$expression ? $value1 : $value2
The ternary operator works like a function, e.g. it returns a value.
Which value? That's where the first parameter comes into play. It is an expression that is evaluated either to true or false.
If it is true, the second parameter is returned as a value. If it is false, the third parameter is returned.
Since you are dealing with strings on the outside, the returned value will be used as a string. It is a very good idea to only return string values then and not confuse the reader of your code with returning NULL. It would be converted to an empty string nonetheless.
Shortcut ternary operator
$expression ?: $value
This one omits the second value for true, and returns $expression if this evaluates to true, or $value otherwise. This works great for checking whether a variable has been defined and set to a value (other than those that evaluate to false), and use a default value otherwise.
By reversing an expression is is possible to omit a parameter, but it is not possible to return an empty string or something else in your case.
$avatar_size <= 50 ?: ' style="overflow:hidden"'
This does not work because if the avatar size is below 50, a "true" would be returned and be used inside the string - which converts to "1".
I've been working with PHP for quite a while now, but this was always a mystery to me, the correct use of the exclamation mark (negative sign) in front of variables.
What does !$var indicate? Is var false, empty, not set etc.?
Here are some examples that I need to learn...
Example 1:
$string = 'hello';
$hello = (!empty($string)) ? $string : '';
if (!$hello)
{
die('Variable hello is empty');
}
Is this example valid? Would the if statement really work if $string was empty?
Example 2:
$int = 5;
$count = (!empty($int)) ? $int : 0;
// Note the positive check here
if ($count)
{
die('Variable count was not empty');
}
Would this example be valid?
I never use any of the above examples, I limit these if ($var) to variables that have boolean values only. I just need to know if these examples are valid so I can broaden the use of the if ($var) statements. They look really clean.
Thanks.
if(! $a) is the same as if($a == false). Also, one should take into account that type conversion takes place when using == operator.
For more details, have a look into "Loose comparisons with ==" section here. From there it follows, that for strings "0" and "" are equal to FALSE ( "0"==false is TRUE and ""==false is TRUE, too).
Regarding posted examples:
Example 1
It will work, but you should note, that both "0" and "" are 'empty' strings.
Example 2
It will work
It's a boolean tester. Empty or false.
It's the not boolean operator, see the PHP manual for further detail.
I'm trying to improve my coding ninja h4x skills, and I'm currently looking at different frameworks, and I have found sample code that's pretty hard to google.
I am looking at the FUEL framework used in a project.
The sample I don't understand is
$data and $this->template->set_global($data);
What is the and keyword doing in this line of code? It is used many places in the framework and it's the first that I have found that uses it.
This is a type of "short circuit evaluation". The and/&& implies that both sides of the comparison must evaluate to TRUE.
The item on the left of the and/&& is evaluated to TRUE/FALSE and if TRUE, the item on the right is executed and evaluated. If the left item is FALSE, execution halts and the right side isn't evaluated.
$data = FALSE;
// $this->template->set_global($data) doesn't get evaluated!
$data and $this->template->set_global($data);
$data = TRUE;
// $this->template->set_global($data) gets evaluated
$data and $this->template->set_global($data);
Note these don't have to be actual boolean TRUE/FALSE, but can also be truthy/falsy values according to PHP's evaluation rules. See the PHP boolean docs for more info on evaluation rules.
When you use logical operators, operands (the value on the left and the value on the right) are evaluated as boolean, so basically that code will do this, in a shorter way:
$o1 = (Bool)$data; // cast to bool
if($o1)
$o2 = (Bool)$this->template->set_global($data); // cast to bool
Edit:
Some additional information:
$a = 33;
isset($a) && print($a) || print("not set");
echo "<br>";
isset($a) AND print($a) OR print("not set");
echo "<br>";
Try to comment/decomment $a = 33;. This is the difference between && and AND, and between || and OR (print returns true that is casted to "1" when converted to string).
It is a valid statement and works like this:
If $data is valid (is not '', 0 or NULL) then run $this->template->set_global($data)
It's a quick way of saying:
if ($data)
{
$this->template->set_global($data);
}
Btw you can also use && instead of and
PHP supports both && and and for the logical AND operation, and they generally work identically, except and has a slightly lower operator precedence than &&: http://php.net/manual/en/language.operators.precedence.php
It's a boolean operator which means it takes two operands and returns a boolean value-- true or false. If both operands evaluate to true (anything but and empty string, zero or null in PHP) it will return true, otherwise the result will be false.
Here's PHP's official docs on the and operator: http://www.php.net/manual/en/language.operators.logical.php
<?php
$a = true and false; # FALSE
$b = true and 5; # TRUE
$c = '' and 0; # FALSE
$d = null and true; # FALSE
?>
I am trying to write would be a simple if condition.
function genderMatch($consumerid1, $consumerid2)
{
$gender1=getGender($consumerid1);
$gender2=getGender($consumerid2);
echo $gender1;
echo $gender2;
if($gender1=$gender2)
echo 1;
return 1;
else
echo 0;
return 0;
}
The output of the getGender function is either a M or F. However, no matter what I do gender1 and gender2 are returned as the same. For example I get this output: MF1
I am currently at a loss, any suggestions?
if ($gender1 = $gender2)
assigns the value of $gender2 to $gender1 and proceeds if the result (i.e. the value of $gender2) evaluates to true (every non-empty string does). You want
if ($gender1 == $gender2)
By the way, the whole function could be written shorter, like this:
function genderMatch($cid1, $cid2) {
return getGender($cid1) == getGender($cid2);
}
You have to put two == for comparison. With only one, as you have right now, you are assigning the value to the first variable.
if($gender1=$gender2)
would become
if($gender1==$gender2)
this:
if($gender1=$gender2)
should be
if($gender1==$gender2)
notice the extra ='s sign. I think you might also need curly brackets for multiple lines of an if/else statement.
Your using the assignment operator = instead of comparsion operators == (equal) or === (identical).
Have a look at PHP operators.
You have some structural problems with your code as well as an assignment instead of a comparison.
Your code should look like this:
function genderMatch($consumerid1, $consumerid2){
$gender1=getGender($consumerid1);
$gender2=getGender($consumerid2);
echo $gender1;
echo $gender2;
if($gender1==$gender2){
echo 1;
return 1;
}else{
echo 0;
return 0;
}
}
Notice the double '=' signs in the if statement. This is a comparison. A single '=' is an assignment. Also, if you want to execute more than 1 line of code with an if/else, you need brackets.
You are using a single = which sets the variable, ie. the value of $gender1 is set to be the value of $gender2.
Use the === operator instead: if($gender1 === $gender2). It is usually a good idea to do strict comparisons rather than loose comparisons.
Read more about operators here: php.net
Another alternative is to use strcmp($gender1, $gender2) == 0. Using a comparer method/function is more common in languages where the string-datatype isnĀ“t treated as a primary data-type, eg. C, Java, C#.