PHP String’s unusual behaviour

Hi Friends,

A post after very long time. Actually busy with work.

While working I found some unusual behavoir of the PHP string with ++ operator. So I think it would be good to share.

Its a simple PHP question, what will be output of below PHP code:

<?php
    $char = 'a';
    print ++$char;
?>

It will Print single line output:

b
b

This is because, it treats strings more like as char type as C or Java. PHP have some unusual (special) behaviour when it comes with strings and increment operator.

I am going to show thoseĀ behaviorsĀ :

<?php
    $char = 'z';
    echo ++$char;
?>

Guess what will above print? Does that product error or will it print ‘{‘ a next sequencial character of ‘z’? But actually none of these is correct. It will print ‘aa’.

But why this? With character and increment when we come to z then it will print aa, ab, ac and so on.

<?php
$char = 'aa';
print ++$char . PHP_EOL;

$char = 'matt';
print ++$char . PHP_EOL;
?>

in above code first it will print ‘ab’ and second will print ‘matu’.

Now lets check with decrement operator:

<?php
    $char ='z';
    print --$char;
?>

Guess what will this do? if you are guessing ‘y’ then you are wrong. It will print ‘z’.

So basically character does not have any effect of decrement operator.

Hope you like this? Let me know your thoughts by discussion here or by commenting on this page.

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by: