chickennugt Posted December 12, 2016 Share Posted December 12, 2016 I'm practicing and this is the pattern I'm trying to create to echo in php: ** ** * ** * * ** * * * * I don't now how to start, i thought it would be easy but im stuck. what do i put for the html and use a while loop? <html> <head> </head> <body> "*" <br> "**" <br> "***" <br> "****" <br> "*****" <?php ?> </body> </html> Quote Link to comment https://forums.phpfreaks.com/topic/302723-newbiehow-can-i-use-a-for-loop-and-echo-this-statement-to-create-this-pattern-in-php/ Share on other sites More sharing options...
benanamen Posted December 13, 2016 Share Posted December 13, 2016 (edited) <?php for ($i = 1; $i <= 5; $i++) { for ($j = 1; $j <= $i; $j++) { echo "*"; } echo "<br />"; } ?> Edited December 13, 2016 by benanamen Quote Link to comment https://forums.phpfreaks.com/topic/302723-newbiehow-can-i-use-a-for-loop-and-echo-this-statement-to-create-this-pattern-in-php/#findComment-1540250 Share on other sites More sharing options...
NotionCommotion Posted December 13, 2016 Share Posted December 13, 2016 Hi chickennugt, Can you tell us why benanamen's solution works or have any questions why it does what it does? Quote Link to comment https://forums.phpfreaks.com/topic/302723-newbiehow-can-i-use-a-for-loop-and-echo-this-statement-to-create-this-pattern-in-php/#findComment-1540251 Share on other sites More sharing options...
codefossa Posted December 13, 2016 Share Posted December 13, 2016 (edited) As an alternative to what's shown above, here's another option: <?php $start = 1; $end = 5; // Using str_repeat() for ($i = $start; $i <= $end; $i++) { echo str_repeat('*', $i) . "\n"; } // Going Both Ways $dir = 1; for ($i = $start; $i > 0 && $i <= $end; $i += $dir) { echo str_repeat('*', $i) . "\n"; if ($i == $end) $dir = -1; } ?> The First Option Output: * ** *** **** ***** The Second: * ** *** **** ***** **** *** ** * Edited December 13, 2016 by Xaotique Quote Link to comment https://forums.phpfreaks.com/topic/302723-newbiehow-can-i-use-a-for-loop-and-echo-this-statement-to-create-this-pattern-in-php/#findComment-1540255 Share on other sites More sharing options...
benanamen Posted December 13, 2016 Share Posted December 13, 2016 Another version <?php $i = 1; while ($i <= 5) { echo str_pad('', $i, '*') . '<br>'; $i++; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/302723-newbiehow-can-i-use-a-for-loop-and-echo-this-statement-to-create-this-pattern-in-php/#findComment-1540256 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.