PHP Gotcha I
Weird comparison
$a = 'foo';
var_dump($a == 0); // true or false?
Increasing/Decrementing Operators
Do you think that$i = $i + 1;
is the same as:
++$i; // or $i++;
Well, there can be big difference.
$name = 'Matok';
++$name;
var_dump($name); // what is value of $name?
Secret operator in PHP
Has PHP secret operator -->
?
$x = 10;
while ($x --> 0) {
echo $x."\n";
}
Solution: Weird comparison
The result is true
Explanation: When you compare string and integer than PHP makes firstly implicit conversion string to integer. So if (int) 'foo'
is 0, then 0 is equal 0. Personally, I use identity ===
whenever is possible.
Solution: Increasing/Decrementing Operators
The result is Matol
Explanation: It's the way PHP is working. You can use ++
/ --
with string and it's alphabetically increase / decrease value. Funny can be the code
$str = 'az';
++$str;
..where the result is ba. In case of 'zz'
the result will be aaa. Well, is't easy to make algorithm to brute-force password in PHP :D.
Solution: Secret operator in PHP
The answer is No It's no secret, just spaces are little fucked up, it's the same:
$x = 10;
while ($x-- > 0) {
echo $x."\n";
}
I'm foreigner. Where I live my friends call me Maťok.