Loop a 2 letter range

人盡茶涼 提交于 2019-12-11 22:15:53

问题


I'm trying to achieve a loop over all possible 2 letter combinations. Something like

foreach(range(aa,zz) as $i) {...}

My current solution is:

foreach (range(a, z) as $first) {
    foreach (range(a, z) as $second) {
        //all 2 letter combinations
        echo $first.$second;
    }
}

This makes me worry that if I needed all possible 10 letter combinations, there would be 10 loops involved.

Is there a better way to achieve this?


回答1:


You could loop over letters using a simple for loop :

for ($letter = 'aa'; $letter != 'aaa'; ++$letter) {
  echo $letter . '<br>';
}

Output :

aa
ab
...
zy
zz



回答2:


$a = array(1,2,3,4,5,6,7,8,9,0);
$b = array('q','r','s','t','u','v','w','x','y','z');
for($i = 26;$i <= 1000;$i++)
    echo str_replace($a,$b,base_convert ( $i, 10 , 26))."<br />";

just put in the right starting and end positions.



来源:https://stackoverflow.com/questions/25687913/loop-a-2-letter-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!