I have a doubt with a few lines of PHP.
I have the following code:
// returns TRUE if a day is festive, FALSE otherwise
$festive = isFestive();
//
$workingDay = $d>0 && !$festive;
Is $workingDay = $d>0 && !$festive the same as writing $workingDay = $d>0 && $festive==FALSE; ?
Any help is appreciated.
Yes, it is.
It is different if you instead do: $festive === FALSE since in that case, values of $festive that are "falsy" will not return true, since they not exactly FALSE.
It's all about data types and how PHP will treat different values of non-boolean types as "false". Check out the follow snippet to illustrate this:
<?php
$test = false;
$test2 = null;
$test3 = 0;
$test4 = '';
$test5 = array();
var_dump($test == false);
var_dump($test2 == false);
var_dump($test3 == false);
var_dump($test4 == false);
var_dump($test5 == false);
var_dump($test === false);
var_dump($test2 === false);
var_dump($test3 === false);
var_dump($test4 === false);
var_dump($test5 === false);
And the resulting output (formatted):
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)
bool(false)
bool(false)
Any if() expression is evaluated to be either false or true. If expression is not explicitly Boolean, then it is converted to boolean and then evaluated. Here is how PHP converts certain types to boolean. In general, if value (numeric, non-boolean) is non zero, it is considered TRUE. See this document to find out more on how PHP evaluates expressions.
So in your case $d>0 evaluates to boolean depending on $d real value, while for !$festive the $festive is first converted to boolean and then negated (!, i.e. if $festive is numberic value 2, then it is converted to TRUE (non-zero) and then negated so the !$festive expression evaluates to FALSE.
Additional note: since your logical condition is AND (&&), if $d>0 is evaluated to false the !$festive will not be evaluated as due to Boole's algebra false && <anything> is always false.
Related
I want to compare strings in an multi dimensional PHP ARRAY
I ran the Debugger and it jumps into the if condition but in my opinion it should not.
$strEmpty = $this->areStringsEmpty($needle, $haystack[$i]); // FALSE after method call
$one=strcasecmp($haystack[$i][0],$needle[0]); // evaluates to 6 , which shoult be FALSE
$two=strcasecmp($haystack[$i][1], $needle[1]); //evaluates to 2 , which alse should be false
if (!$strEmpty && $one && $two) { // TRUE && FALSE && FALSE
return TRUE;
}
why is this so ?
I know i could check against 0 in the condition , but i am wondering why this isnt done automatically.
strcasecmp returns 0 when the string matches. To get a boolean true when the strings match, you can do this.
$one=(strcasecmp($haystack[$i][0],$needle[0]) === 0); //TRUE when === 0
$two=(strcasecmp($haystack[$i][1], $needle[1]) === 0); //TRUE when === 0
The thing is, strcasecmp returns numbers. So it'll be true if the return is greater or lower than 0.
Input:
$var1 = "Hello";
$var2 = "hello2";
if (strcasecmp($var1, $var2) == true) {
var_dump(strcasecmp($var1, $var2));
}
Output:
int(-1)
As you can see, it's -1, but it's true.
You could simply add braces around the strcasecmp.
$one = (strcasecmp($haystack[$i][0], $needle[0]) == 0);
$two = (strcasecmp($haystack[$i][1], $needle[1]) == 0);
This will give you true if it's equal, false if it's not.
Example
i couldn't understand why i am getting the output "1" from the below statement in PHP,
<?php echo !!!0;?>
please let me know the reason
The statement is parsed as !(!(!0)). ! is the logical negation operator. When applying it to any other type than a boolean (true/false), the operand is first cast to a boolean value (0, empty string, empty array, null, empty SimpleXML objects = false; everything else true).
Let's break the statement down:
!!!0 ==
!!!false ==
!!true ==
!false ==
true
Finally, echo true will output 1.
Because PHP "casts" the 0 to a boolean when doing a logic operation.
So !0 is 1
!1 is 0
!0 is 1
! is used to negate statements (post-evaluated).
0 evaluates to false => true (1) => false (0) => true (1)
! ! !
Why is a number cast to boolean?
This happens implicitly by using !, the exclamation mark expects yes true or no false and so the value next to it gets automatically cast to something that fits this condition (yes or no).
You can make similiar experiments using:
var_dump( !"hello world" );
// ...
Explicit casts are done by putting the type in brackets: (boolean)1 === true
Update for #user2864740:
<?php
var_dump(!0 === true); // bool(true)
var_dump(!(0) === true); // bool(true)
var_dump((!0) === true); // bool(true)
var_dump((boolean)1 === true); // bool(true)
var_dump((boolean)1); // bool(true)
Update after discussion:
echo true; prints 1. But this does not change a variable for example:
$x = true;
echo $x; // 1
var_dump($x); // bool(true)
I'm new to PHP and I found in my code, when I pass a FALSE to a function. It converted to null immediately. I've read some articles knowing that False and null are equal. But I don't know when this conversion happens.
Below is my code
function equal($expected, $actual){
if($expected == $actual) { //... }
}
function foo(){
$signal = getSignal();
equal(FALSE, $signal->good); //...
}
You will need to use triple equal signs === for equality. For example
false == null; // true
false === null; // false
0 == false; // true
0 === false; // false
Check the docs on comparison operators
No, they are NOT converted. You can var_dump($variable) at any time to see both the type and the value of $variable any time. But there are a few things which evaluates to false with the == comparison operator. So in fact false == null will evaluate to true just as false == 0 or false == "0" in PHP. This is why the comparison operator === comes into the picture - using that instead of == in above example, all will evaluate to false instead of true.
For more information, see http://php.net/manual/en/language.operators.comparison.php
Can't get the point of === and !== with primitive types:
$a === $b TRUE if $a is equal to $b, and they are of the same type.
$a !== $b TRUE if $a is not equal to $b, or they are not of the same type.
The assuming that $request->getMethod() returns GET or POST (as string) and that $form->isValid() returns a boolean true or false, the following code:
if('POST' === $request->getMethod() || (false === $form->isValid())) :
endif;
Does make any sense in respect of this shorter one:
if('POST' == $request->getMethod() || !$form->isValid()) :
endif;
You have truty and falsy values in PHP. For instance, 0, '', array() are falsy values. If you use == it will match those values with the truty/falsy values:
var_dump(true == 'hello'); // true because a not empty string is a truty value
var_dump(false == 0); // true
=== will match not only the value but the type also:
var_dump(true === 'hello'); // false, true is a boolean and 'hello' a string
var_dump(false === 0); // false, false is a boolean and 0 is a string
This will become a problem when a function can return 0 or false, strpos for example.
There are also other factors with the ==. It will type cast values to a int if you compare 2 different types:
var_dump("123abc" == 123); // true, because '123abc' becomes `123`
This will be problematic if you compare a password: http://phpsadness.com/sad/47
They are sometimes necessary. For example when using strpos to check if a string is contained in another string you have to distinguish 0 from false.
wrong:
if(strpos($haystack,$needle))...
right:
if(strpos($haystack,$needle) !== false)...
== will sometimes have odd behavior when comparing different types. E.g. 'POST' would be considered equal to 0. That's why many people usually use ===, it avoids type-juggling problems.
In your case it shouldn't make a difference though.
although it may not be needed,
(false===$form->isValid())
and
!$form->isValid()
are not the same as the first is checking to see if the value of $form->isValid() is false, while the second is checking if $form->isValid() is a falsey value, so for example if $form->isValid() returns null then the first statement will not evaluate to true while the second one will evluate to true.
I have been programming in PHP for a while but I still dont understand the difference between == and ===. I know that = is assignment. And == is equals to. So what is the purpose of ===?
It compares both value and type equality.
if("45" === 45) //false
if(45 === 45) //true
if(0 === false)//false
It has an analog: !== which compares type and value inequality
if("45" !== 45) //true
if(45 !== 45) //false
if(0 !== false)//true
It's especially useful for functions like strpos - which can return 0 validly.
strpos("hello world", "hello") //0 is the position of "hello"
//now you try and test if "hello" is in the string...
if(strpos("hello world", "hello"))
//evaluates to false, even though hello is in the string
if(strpos("hello world", "hello") !== false)
//correctly evaluates to true: 0 is not value- and type-equal to false
Here's a good wikipedia table listing other languages that have an analogy to triple-equals.
It is true that === compares both value and type, but there is one case which hasn't been mentioned yet and that is when you compare objects with == and ===.
Given the following code:
class TestClass {
public $value;
public function __construct($value) {
$this->value = $value;
}
}
$a = new TestClass("a");
$b = new TestClass("a");
var_dump($a == $b); // true
var_dump($a === $b); // false
In case of objects === compares reference, not type and value (as $a and $b are of both equal type and value).
The PHP manual has a couple of very nice tables ("Loose comparisons with ==" and "Strict comparisons with ===") that show what result == and === will give when comparing various variable types.
It will check if the datatype is the same as well as the value
if ("21" == 21) // true
if ("21" === 21) // false
=== compares value and type.
== doesn't compare types, === does.
0 == false
evaluates to true but
0 === false
does not
Minimally, === is faster than == because theres no automagic casting/coersion going on, but its so minimal its hardly worth mentioning. (of course, I just mentioned it...)
It's a true equality comparison.
"" == False for instance is true.
"" === False is false