PHP compare boolean values - php

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

Related

Why PHP condition getting true even if i am checking equal to

<?php
$test = "-3,-13";
if ($test == -3) {
echo "yay";
} else {
echo "nay";
}
?>
why it always runs through if condition and not going in else condition? I am new to php so do not know what's going on here.
The string is converted into an integer "-3, 46, blala" -> -3 , then the condition is evaluated.
Use the === operator to avoid conversion.
Most of the time, you do not want to let php do the conversion in your place (security problem). Rather, the request is refused.
As PHP documentation says
Example Name Result
$a == $b Equal TRUE if $a is equal to $b after type juggling.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type.
When we compare a number with a string, the string is converted to a number and the comparison performed numerically.
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
https://www.php.net/manual/en/language.operators.comparison.php

Is !$festive the same as $festive==FALSE?

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.

Not equal to != and !== in PHP

I've always done this: if ($foo !== $bar)
But I realized that if ($foo != $bar) is correct too.
Double = still works and has always worked for me, but whenever I search PHP operators I find no information on double =, so I assume I've always have done this wrong, but it works anyway. Should I change all my !== to != just for the sake of it?
== and != do not take into account the data type of the variables you compare. So these would all return true:
'0' == 0
false == 0
NULL == false
=== and !== do take into account the data type. That means comparing a string to a boolean will never be true because they're of different types for example. These will all return false:
'0' === 0
false === 0
NULL === false
You should compare data types for functions that return values that could possibly be of ambiguous truthy/falsy value. A well-known example is strpos():
// This returns 0 because F exists as the first character, but as my above example,
// 0 could mean false, so using == or != would return an incorrect result
var_dump(strpos('Foo', 'F') != false); // bool(false)
var_dump(strpos('Foo', 'F') !== false); // bool(true), it exists so false isn't returned
!== should match the value and data type
!= just match the value ignoring the data type
$num = '1';
$num2 = 1;
$num == $num2; // returns true
$num === $num2; // returns false because $num is a string and $num2 is an integer
$a !== $b TRUE if $a is not equal to $b, or they are not of the same type
Please Refer to http://php.net/manual/en/language.operators.comparison.php
You can find the info here: http://www.php.net/manual/en/language.operators.comparison.php
It's scarce because it wasn't added until PHP4. What you have is fine though, if you know there may be a type difference then it's a much better comparison, since it's testing value and type in the comparison, not just value.

php 5 strpos() difference between returning 0 and false?

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 === do in PHP

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

Categories