Increase letters in PHP?

4

Recently I needed to increment letters in PHP within a loop repetition.

For each iteration, instead of numerical indices, it needed letters of the alphabet.

So, as I already know that PHP does incremental letters (and to be very simple), I did something like that.

for($letra = 'a'; $letra != 'aa'; $letra++) {

    echo $letra;
}

// abcdefghijklmnopqrstuvwxyz

However, because I have never seen this documented and in any other language I know of such functionality, I was in doubt whether to use it or not.

Because of coding (and so on), is it safe to use this feature, or is it better to appeal to friends chr or range('a', 'z') , as in the example below?

for($letra = 97; $letra <= 122; $letra++) {

    echo chr($letra);
}

//abcdefghijklmnopqrstuvwxyz


echo implode('', range('a', 'z')); //abcdefghijklmnopqrstuvwxyz

//abcdefghijklmnopqrstuvwxyz
    
asked by anonymous 04.02.2015 / 20:40

3 answers

6

This is typical of weakly typed C-language, for example. One type can be used as if it were another. Note that this is different from being dynamically typed, so much so that C is statically typed (and behaves a bit differently).

At first there are no problems. It does not cause errors of any kind. It is only recommended to avoid this feature when it is possible because it is easy to use wrongly. Of course in simple situations like this it's hard to miss.

If it is possible to say explicitly what the intention is (working with characters) is somewhat better from the viewpoint of readability. Anyone who does not know this feature may be surprised by the first code of the question. But to say that it is wrong is priceless.

I know it's just an example but in this case I would even use a string literal:)

    
04.02.2015 / 20:51
1

As already mentioned, this is characteristic of poorly typed languages. this works because increment is done in the ASCII(A-Z 65-90, a-z 97-122) code, not exactly in the letter you see. This works only with increment operator (% with%). With decrementing it is not possible, that is, you can not create a string of z-a Z-A.

The manual talks about this behavior, which follows the Perl which says that the set valid for the increment is (az, AZ and 0-9), so ++ will z , in C it would follow the next ASCII code.

This functionality is useful when assembling the header of a worksheet where the coordinates are ex: aa

Examples in Perl

$char = 'z';
print ++$char; //saída: aa

Equivalent example of range ()

@alfabeto = ('a'..'z');

foreach(@alfabeto){
    print $_
}
    
05.02.2015 / 14:01
0

It's normal to do this, if I were to need a solution like this I would do it this way:

foreach (range('a', 'z') as $letra) {
   print $letra;
}
    
04.02.2015 / 20:54