For example
$x = true;
return (($x ? "!" : "" ). is_null(NULL));
This obviously doesn't work, is there a way to do it?
The goal is to refactor this
$var == true
? array_filter($labels, function($v){return str_contains($v, 'return');})
: array_filter($labels, function($v){return !str_contains($v, 'return');});
Thanks
A common way of describing boolean combinations is as a truth table listing the possible inputs and outputs. In this case:
$x
is_null($var)
Desired result
false
false
false
false
true
true
true
false
true
true
true
false
So, the result you want is "either $x is true, or is_null($var) is true, but not both".
Looking in the PHP manual under "logical operators", we see that that's the definition of the xor operator, so you could write this:
return $x xor is_null($var);
An intermediate variable and simple if statement as shown in Justinas's answer is probably a lot more readable, though. Readability is extremely important in programming, because code is read far more times than it's written.
You can, but with different approach: first execute function and then check if it needs to be inverted
$result = is_null($var);
if ($x) {
// invert result from e.g. true to false
$result = !$result;
}
is_null returns a boolean. $x is a boolean. Compare both booleans:
return is_null($var) != $x;
Related
if(strpos("http://www.example.com","http://www.")==0){ // do work}
I'd expect this to resolve as true, which it does. But what happens when I do
if(strpos("abcdefghijklmnop","http://www.")==0){// do work}
This also passes on php 5 because as far as I can work out the strpos returns false which translates as 0.
Is this correct thinking/behaviour? If so what is the workaround for testing for that a substring is at the beginning of another string?
Yes, this is correct / expected behavior :
strpos can return 0 when there is a match at the beginning of the string
and it will return false when there is no match
The thing is you should not use == to compare 0 and false ; you should use ===, like this :
if(strpos("abcdefghijklmnop","http://www.") === 0) {
}
Or :
if(strpos("abcdefghijklmnop","http://www.") === false) {
}
For more informations, see Comparison Operators :
$a == $b will be TRUE if $a is equal to $b.
$a === $b will be TRUE if $a is equal to $b, and they are of the same type.
And, quoting the manual page of strpos :
This function may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "". Please
read the section on Booleans for
more information. Use the ===
operator for testing the return
value of this function.
=== and !== compare type and value as shown below:
if (strpos("abcdefghijklmnop", "http://www.") !== false) {
// do work
}
strpos returns an int or boolean false. the == operator also evaluates 0 to mean false, you want to use the === operator (three equals signs) that also checks that the types being compared are the same instead of just seeing if they can be evaluated to mean the same.
so
if (strpos($hastack, $needle) === 0)
{
// the $needle is found at position 0 in the $haystack
}
0 is a possible return value from strpos when it finds a match at the very beginning. In case if the match is not found it returns false(boolean). So you need to check the return value of strpos using the === operator which check the value and the type rather than using == which just checks value.
I personally tend to use this way :
if(!strpos($v,'ttp:'))$v='http://'.$v;
or
if(strpos(' '.$v,'http'))
to avoid the "0" position then always make it a number more than 0
cheers
What does the double not operator do in PHP?
For example:
return !! $row;
What would the code above do?
It's not the "double not operator", it's the not operator applied twice. The right ! will result in a boolean, regardless of the operand. Then the left ! will negate that boolean.
This means that for any true value (numbers other than zero, non-empty strings and arrays, etc.) you will get the boolean value TRUE, and for any false value (0, 0.0, NULL, empty strings or empty arrays) you will get the boolean value FALSE.
It is functionally equivalent to a cast to boolean:
return (bool)$row;
It's the same (or almost the same - there might be some corner case) as casting to bool. If $row would cast to true, then !! $row is also true.
But if you want to achieve (bool) $row, you should probably use just that - and not some "interesting" expressions ;)
It means if $row has a truthy value, it will return true, otherwise false, converting to a boolean value.
Here is example expressions to boolean conversion from php docs.
Expression Boolean
$x = ""; FALSE
$x = null; FALSE
var $x; FALSE
$x is undefined FALSE
$x = array(); FALSE
$x = array('a', 'b'); TRUE
$x = false; FALSE
$x = true; TRUE
$x = 1; TRUE
$x = 42; TRUE
$x = 0; FALSE
$x = -1; TRUE
$x = "1"; TRUE
$x = "0"; FALSE
$x = "-1"; TRUE
$x = "php"; TRUE
$x = "true"; TRUE
$x = "false"; TRUE
"not not" is a convenient way in many languages for understanding what truth value the language assigns to the result of any expression. For example, in Python:
>>> not not []
False
>>> not not [False]
True
It can be convenient in places where you want to reduce a complex value down to something like "is there a value at all?".
Another more human, maybe simpler, way to 'read' the not not:
The first '!' does 2 things: 'convert' the value to boolean, then output its opposite. So it will give true if the value is a 'falsy' one.
The second '!' is just to output the opposite of the first.
So, basically, the input value can be anything, maybe a string, but you want a boolean output, so use the first '!'. At this point, if you want TRUE when the input value is 'falsy', then stop here and just use a single '!'; otherwise if you want TRUE when the input value is 'truthy', then add another '!'.
Lets look at
!$a;
Rather than interpreting the ! operator as as taking the
Boolean opposite of the value to its right
read
take the Boolean opposite of the expression to its right
In this case
$a;
could be an expression
so to is
!$a;
so is
!!$a;
and
!!!$a;
and so on, as each of these is a valid expression, the ! operator can be prepended to each of them.
I was just wandering the about the concept of equating the condition in PHP that is,
what could be the difference between
true == isset($variable)
and
isset($variable) == true
?
For this specific case, no difference.
The first syntax is used to prevent accidental assignment instead of comparison.
if ( true = $x ) // would yiled error
if ( $x = true ) // would work
But again, in your case, no difference.
Elaboration:
Say you want to compare a variable $x to true and do something. You could accidentally write
if ( $x = true )
instead of
if ( $x == true )
and the condition would always pass.
But if you get into the habit of writing
if ( true == $x )
these mistakes wouldn't happen, since a syntax error would be generated and you would know in advance.
There is no difference. But isset() itself returns a boolean value.
So never use
if (true == isset($variable))
Just:
if (isset($variable))
Remember that when php parses that true is actually defined and its equal to 1. Furthermore so is false and it is equal to 0. php automatically checks these for comparison with these values in an IF statement. You'll be safe using the ! operator, because its the same as if ($something == false) good luck!
Would it be Java, there was difference.
i.e.
String test = null;
if("".equals(test)){
System.out.println("I m fine..");
}
if(test.equals("")){
System.out.println("I m not fine..");
}
There is no "real" diffrences(in this case)
Between
true == isset($variable) AND
isset($variable) == true
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
?>
What does the double not operator do in PHP?
For example:
return !! $row;
What would the code above do?
It's not the "double not operator", it's the not operator applied twice. The right ! will result in a boolean, regardless of the operand. Then the left ! will negate that boolean.
This means that for any true value (numbers other than zero, non-empty strings and arrays, etc.) you will get the boolean value TRUE, and for any false value (0, 0.0, NULL, empty strings or empty arrays) you will get the boolean value FALSE.
It is functionally equivalent to a cast to boolean:
return (bool)$row;
It's the same (or almost the same - there might be some corner case) as casting to bool. If $row would cast to true, then !! $row is also true.
But if you want to achieve (bool) $row, you should probably use just that - and not some "interesting" expressions ;)
It means if $row has a truthy value, it will return true, otherwise false, converting to a boolean value.
Here is example expressions to boolean conversion from php docs.
Expression Boolean
$x = ""; FALSE
$x = null; FALSE
var $x; FALSE
$x is undefined FALSE
$x = array(); FALSE
$x = array('a', 'b'); TRUE
$x = false; FALSE
$x = true; TRUE
$x = 1; TRUE
$x = 42; TRUE
$x = 0; FALSE
$x = -1; TRUE
$x = "1"; TRUE
$x = "0"; FALSE
$x = "-1"; TRUE
$x = "php"; TRUE
$x = "true"; TRUE
$x = "false"; TRUE
"not not" is a convenient way in many languages for understanding what truth value the language assigns to the result of any expression. For example, in Python:
>>> not not []
False
>>> not not [False]
True
It can be convenient in places where you want to reduce a complex value down to something like "is there a value at all?".
Another more human, maybe simpler, way to 'read' the not not:
The first '!' does 2 things: 'convert' the value to boolean, then output its opposite. So it will give true if the value is a 'falsy' one.
The second '!' is just to output the opposite of the first.
So, basically, the input value can be anything, maybe a string, but you want a boolean output, so use the first '!'. At this point, if you want TRUE when the input value is 'falsy', then stop here and just use a single '!'; otherwise if you want TRUE when the input value is 'truthy', then add another '!'.
Lets look at
!$a;
Rather than interpreting the ! operator as as taking the
Boolean opposite of the value to its right
read
take the Boolean opposite of the expression to its right
In this case
$a;
could be an expression
so to is
!$a;
so is
!!$a;
and
!!!$a;
and so on, as each of these is a valid expression, the ! operator can be prepended to each of them.