Matok's PHP Blog

PHP Gotcha I

article image
I want to write several articles about PHP behavior that can trick you. Truly, I hate this, because I believe if result is not what I expect than code is bad. If you want to ask something from this your candidate on job interview: please don't do it. Solutions are below so scroll carefully :D

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';

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';

..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";

If you like this article then mark it as helpful to let others know it's worth to read. Otherwise leave me a feedback/comment and we can talk about it.

I'm foreigner. Where I live my friends call me Maťok.

Comments - Coming Soon