0

How do I print a sequence of letters with PHP, without using 'for'? It needs to be something like this:

print a sequence of letters

I have a code like this:

<?php $a = 'a'; $n = 50; $i = 0; $k = 0; while ( $i < $n ) { echo $a." ".'<p></p>'; for ($k =0; $k<=$i; $k++) { echo $a." "; } $i++; } ?> 

But I don't need 'for', maybe something with 'while', 'if' or 'foreach'. Ideas?

3
  • The code you have works fine. what are you asking? Commented Dec 13, 2018 at 18:59
  • Your code doesn't work? Commented Dec 13, 2018 at 19:00
  • 1
    You can use str_repeat instead of the for loop. Commented Dec 13, 2018 at 19:00

4 Answers 4

1
<?php print implode( "\n", array_map( function($n) { return str_repeat('a', $n); }, range(1,10) ) ); 

Output:

a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa aaaaaaaaa aaaaaaaaaa 
Sign up to request clarification or add additional context in comments.

Comments

0

One option could be to use a second while loop:

$a = 'a'; $n = 50; $i = 0; while ($i < $n) { $k = -1; $str = ""; while ($k < $i) { $str .= " $a"; $k++; } echo "$str<br>"; $i++; } 

Php demo

Another option could be using str_repeat

while ( $i < $n ) echo str_repeat($a, ++$i) . "<br>"; 

Php demo

Comments

0

Actually I found a way too, thanks for all the answers!

<?php $i=0; $j=50; while($i < $j ) { $j=50; $k=0; while($k <= $i){ echo 'a'; ++$k; } echo "<p></p>"; $i++; } 

And it's easy to understand if you are new to the coding world.

1 Comment

No need for the second assignment to $j.
0

The following are equivalent.

for within for:

<?php for($i=1, $n=10; $i<=$n; $i++) { for($j=1; $j<=$i; $j++) { echo 'a'; } echo "\n"; } 

for and str_repeat:

<?php for($i=1, $n=10; $i<=$n; $i++) echo str_repeat('a', $i), "\n"; 

foreach with a range and str_repeat:

<?php foreach(range(1, 10) as $n) echo str_repeat('a', $n), "\n"; 

Output (for each of the snippets):

a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa aaaaaaaaa aaaaaaaaaa 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.