Usual Error PHP Developers Make: Assuming that PHP supports a character data type
×


Usual Error PHP Developers Make: Assuming that PHP supports a character data type

917

Let's run through an example to understand what is this error all about and review this sample piece of code to try and comprehend what it will print:

For Instance:-

for ($char = 'a'; $char <= 'z'; $char++) {
    echo $char . "\n";
}

While you must be thinking that it would only print ‘a’ through ‘z’, you may be surprised to know that you were wrong. While it would print ‘a’ through ‘z’, but then it will also print ‘aa’ through ‘yz’.

Let’s see why?

In PHP there’s no char datatype, only string is available.

Keeping that in mind, let us increment the string z in PHP yields aa: As shown below

php> $c = 'z'; echo ++$c . "\n";

aa

Now, to further confuse matters, aa is lexicographically less than z:

php> var_export((boolean)('aa' < 'z')) . "\n";

true

Therefore, the example shown above prints the letters a through z, but then also prints aa through yz. And the code stops when it reaches za, which is the first value it encounters that it “greater than” z:

php> var_export((boolean)('za' < 'z')) . "\n";

false

That being the case, let us look through one way that would properly loop through the values ‘a’ through ‘z’ in PHP:

for ($i = ord('a'); $i <= ord('z'); $i++) {
   echo chr($i) . "\n";
}

or alternatively:

$letters = range('a', 'z');
for ($i = 0; $i < count($letters); $i++) {
   echo $letters[$i] . "\n";
}

Thus, it won’t be wrong to state that PHP supports a character data type. But a good PHP developer understands that by deeply understanding the error.

They can find a way-out



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments