在PHP中使用Do while循环通过A-Z循环

时间:2014-04-23 12:11:10

标签: php

我试图通过do while循环循环a-z 我知道我也可以用foreach和forloop做到这一点。

$char = 'a';
do {
   echo $char;
   $char++;

} while ($char <= 'z');

为什么要提供输出:

abcdefghijklmnopqrstuvwxyzaaabacadaeafagahaiajakalamanaoapaqarasatauavawaxayazbabbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzcacbcccdcecfcgchcicjckclcmcncocpcqcrcsctcucvcwcxcyczdadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzeaebecedeeefegeheiejekelemeneoepeqereseteuevewexeyezfafbfcfdfefffgfhfifjfkflfmfnfofpfqfrfsftfufvfwfxfyfzgagbgcgdgegfggghgigjgkglgmgngogpgqgrgsgtgugvgwgxgygzhahbhchdhehfhghhhihjhkhlhmhnhohphqhrhshthuhvhwhxhyhziaibicidieifigihiiijikiliminioipiqirisitiuiviwixiyizjajbjcjdjejfjgjhjijjjkjljmjnjojpjqjrjsjtjujvjwjxjyjzkakbkckdkekfkgkhkikjkkklkmknkokpkqkrksktkukvkwkxkykzlalblcldlelflglhliljlklllmlnlolplqlrlsltlulvlwlxlylzmambmcmdmemfmgmhmimjmkmlmmmnmompmqmrmsmtmumvmwmxmymznanbncndnenfngnhninjnknlnmnnnonpnqnrnsntnunvnwnxnynzoaobocodoeofogohoiojokolomonooopoqorosotouovowoxoyozpapbpcpdpepfpgphpipjpkplpmpnpopppqprpsptpupvpwpxpypzqaqbqcqdqeqfqgqhqiqjqkqlqmqnqoqpqqqrqsqtquqvqwqxqyqzrarbrcrdrerfrgrhrirjrkrlrmrnrorprqrrrsrtrurvrwrxryrzsasbscsdsesfsgshsisjskslsmsnsospsqsrssstsusvswsxsysztatbtctdtetftgthtitjtktltmtntotptqtrtstttutvtwtxtytzuaubucudueufuguhuiujukulumunuoupuqurusutuuuvuwuxuyuzvavbvcvdvevfvgvhvivjvkvlvmvnvovpvqvrvsvtvuvvvwvxvyvzwawbwcwdwewfwgwhwiwjwkwlwmwnwowpwqwrwswtwuwvwwwxwywzxaxbxcxdxexfxgxhxixjxkxlxmxnxoxpxqxrxsxtxuxvxwxxxyxzyaybycydyeyfygyhyiyjykylymynyoypyqyrysytyuyvywyxyyyz

而不只是:

abcdefghijklmnopqrstuvwxyz

5 个答案:

答案 0 :(得分:8)

来自documentation

  

PHP在处理字符变量而不是C的算术运算时遵循Perl的约定。例如,在PHP和Perl $a = 'Z'; $a++;中将$a变为'AA',而在C a = 'Z'; a++;中将变为'['(ASCII值为'Z'是90,'['的ASCII值是91)。请注意,字符变量可以递增但不递减,即使只支持纯ASCII字母和数字(a-z,A-Z和0-9)。

尝试这样的事情:

for($i = 0, $char = 'a'; $i < 26; $i++, $char++) {
   echo $char;
}

答案 1 :(得分:4)

您无法将z26或某种数字进行比较。你需要一些东西来比较它。函数ord()就是这样做的。所以,你可以这样做:

$char = 'a';
do {
   echo $char;
   $char++;

} while (ord($char) <= ord('z'));

答案 2 :(得分:4)

由于

<?php

$char = 'z';

var_dump(++$char); //string(2) "aa"

var_dump('aa' <= 'z'); //bool(true)
var_dump('za' <= 'z'); //bool(false)

DEMO

就个人而言,我只使用从97(a的ascii值)到122(z的ascii值)的循环:

for ($i = 97; $i <= 122; $i++) {
    echo chr($i);
}

答案 3 :(得分:0)

上面的选项的替代方法是下面的代码。

   <?php
    $i = '0';
    while($i < '26') {
    echo chr(97 + $i);
    $i++;
   ?>

答案 4 :(得分:0)

<?php
foreach(range('a', 'z') as $char) {
    echo "$char ";
}

简单范围a-z视图。