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:
[cc lang=”php”]
[/cc]
It will Print single line output:
[cc lang=”php”]
b
[/cc]
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 :
[cc lang=”php”]
[/cc]
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.
[cc lang=”php”]
[/cc]
in above code first it will print ‘ab’ and second will print ‘matu’.
Now lets check with decrement operator:
[cc lang=”php”]
[/cc]
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.
[…] This post was mentioned on Twitter by Avinash Zala and Avi. Avi said: Xpert Developer | PHP String’s unusual behaviour http://goo.gl/fb/6qs9O […]
Hi Avi,
Nice post..
good to know about string behavior with ++ operator
Interesting, but who the hell actually uses increment/decrement on strings?
If you really are needing that behavior use ord() and chr() or something and do math on the actual ASCII values.
Nice and interesting to see this …
I accidentally found something interesting using the += operator. I wanted to append the percent sign to a tax rate (which is being returned as a string object). So if my tax rate is 8.750000, I was going to stick the % at the end of it tonight and work on trimming the excess zeros tomorrow, because it’s late. But because it’s late, I wrote this line of code: $taxrate += ‘%’. That didn’t add the percent at the end (obviously), but it trimmed the zeros off the the number. So by adding these 2 lines of code, I’m able to turn 8.750000 into 8.75%:
$taxrate += ‘%’; //trims excess zeroes off the end of a string.
$taxrate = $taxrate.’%’; //adds the percent at the end of the number
Weird, but whatever works.
yes really interesting, thanks for sharing your work experience with us.