0

我刚开始在工作中学习 PHP,并被要求以大写和小写输出字母。这需要在一个页面上重复 10 次。

这是我放在一起的代码,但是必须有更简单的方法来重复此操作,而不是复制并粘贴 10 次。

<?php
for ($i=65; $i<=90; $i++) {
$Letter = chr($i);
print $Letter .", ";
}
for ($i=97; $i<=122; $i++) {
$Letter = chr($i);
print $Letter .", ";
}
?>

一位朋友告诉我最好使用 For 循环而不是 foreach 循环。

4

6 回答 6

6
<?php
for ($a = 1; $a <= 10; $a++)
{
    for ($i=65; $i<=90; $i++) {
    $Letter = chr($i);
    print $Letter .", ";
    }
    for ($i=97; $i<=122; $i++) {
    $Letter = chr($i);
    print $Letter .", ";
    }
}
?>

甚至更好:

<?php
for ($a = 1; $a <= 10; $a++)
{
    echo implode(', ', range('A','Z'));
    echo implode(', ', range('a','z'));
}
?>
于 2013-04-28T11:17:52.957 回答
1
print substr(str_repeat(implode(", ", array_merge(range('a', 'z'), range('A', 'Z'))).", ", 10), 0, -2);

这是我能想象的最短的方式。

但是你可以做的只是在你的代码周围放一个 for 循环:

for ($repeat_times = 10; $repeat_times; $repeat_times--)
    for ($i=65; $i<=90; $i++) {
        $Letter = chr($i);
        print $Letter .", ";
    }
    for ($i=97; $i<=122; $i++) {
        $Letter = chr($i);
        print $Letter .", ";
    }
}
于 2013-04-28T11:19:48.840 回答
1

使用forforeachcicles 的解决方案:

<?php
$prints = 10;
$alphas = array_merge(range('A', 'Z'), range('a', 'z'));

for ($i = 1; $i <= $prints; $i++) {
  echo "$i\n";
  foreach ($alphas as $letter) {
    echo "{$letter} ";
  }

  echo "\n\n";
}

只需按照echo说明更改输出即可。

于 2013-04-28T11:20:29.267 回答
1
Try this: using an additional loop at the top, solves the problem:

<?php
for ($count=0; $count<10; $count++) {
    for ($i=65; $i<=90; $i++) {
        $Letter = chr($i);
        print $Letter .", ";
    }
    for ($i=97; $i<=122; $i++) {
        $Letter = chr($i);
        print $Letter .", ";
    }
    echo "<br/>";
}
?>

或者您也可以通过以下方式执行相同操作:

<?php
for ($a = 1; $a <= 10; $a++) {
    echo implode(', ', range('A','Z'));
    echo " | ".implode(', ', range('a','z'));
    echo "<br/>";
}
?>
于 2013-04-28T11:21:52.190 回答
0

不要使用字符数组。字符串已经是一个数组。

<?php
$letters = "abcdefghijklmnopqrstuvwxyz";

$repeat = 0;

while($repeat < 10)
{
    for($i = 0; $i < strlen($letters); $i++){
        echo strtoupper($letters[$i]). "<br>";
    }

    for($i = 0; $i < strlen($letters); $i++){
        echo $letters[$i]. "<br>";
    }

    $repeat++;
}
于 2013-04-28T11:31:49.630 回答
0

怎么样:

<?php
    for ($j= 0; $j < 10; $j++) {
        for ($i=65; $i<=90; $i++) {
        $Letter = chr($i);
        print $Letter .", ";
        }
        for ($i=97; $i<=122; $i++) {
        $Letter = chr($i);
        print $Letter .", ";
        }
    }
?>
于 2013-04-28T11:16:11.103 回答