1

I need your help to solve this problem, I am trying to write the necessary code so that the output is as follows:

PHP! PHP!! PHP!!! PHP!!!! PHP!!!!!

<?php
$y = ['!'];
for($i = 1; $i <= 5; $i++)
{   
    print "PHP!"."$y\t";
    if($y+1 <5)
    $y="!";    
    $y+'!';
 }
?>

Until the second word, it adds one more exclamation point and in the rest of the repetitions it has the same number, that is two exclamation points. How can I solve this problem?

  • Define a string that only contains `PHP`. Write a loop that [concatenates](https://stackoverflow.com/questions/8336858/how-to-combine-two-strings-together-in-php) an exclamation mark at the end and output. – El_Vanja Feb 17 '21 at 14:03
  • There are several issues here. 1. You define `$y` as an array before the loop. 2. You try and print `$y` (which is an array in the first iteration), which should throw a "array to string conversion" warning. 3. `$y+1 < 5` should probably be `$i+1 < 5` . 4. Neither `$y` or `!` are numbers so using them as a mathematical expression (`$y+'!'`) doesn't make sense (if you're trying to push it to the array, it should be `$y[] = '!'` but remember that the line above would set `$y` as a string, not an array.) – M. Eriksson Feb 17 '21 at 14:07
  • Make sure that you [show all errors and warnings](https://stackoverflow.com/questions/5438060/showing-all-errors-and-warnings) while developing. When testing your code, it throws both warnings and fatal errors. Demo: https://3v4l.org/603tP – M. Eriksson Feb 17 '21 at 14:11

2 Answers2

1

Try this:

<?php
for ($i = 0; $i < 5; $i++) {
    echo "PHP".str_repeat ("!", $i);
}
?>

Florian
  • 66
  • 4
0

You can try it:

<?php

for($i = 1; $i <= 5; $i++)
{   
    echo "PHP";
    for($j = 1; $j <= $i; $j++){
        echo "!";
    }
 }

?>

You can also use str_repeat():

<?php
for ($i = 1; $i <= 5; $i++) {
    echo "PHP".str_repeat ("!", $i);
}
?>

Output will be: PHP!PHP!!PHP!!!PHP!!!!PHP!!!!!

Humayun Ahmad Rajib
  • 1,502
  • 1
  • 10
  • 22