1

I am trying to create a program that allows an array, that contains integers and strings, to be passed to the draw_stars() function. When a string is passed, instead of displaying *, display the first letter of the string according to the example below.

For example:

$x = array(4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith");
draw_stars($x) should print the following on the screen/browser:

Here's my code so far:

$y = array(4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith");
function draw_stars2($ropes){ 
    foreach ($ropes as $rope) {
        echo str_repeat('*', $rope), '<br />'; 
    } 
}

$output2 = draw_stars2($y);
echo $output2;

Any idea?

3
  • What's your intended output? Commented Jul 4, 2015 at 5:24
  • $x = array(4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"); draw_stars($x) should print the following on the screen/browser: Commented Jul 4, 2015 at 5:27
  • 1
    "draw_stars($x) should print the following on the screen/browser", what's following? Commented Jul 4, 2015 at 5:28

1 Answer 1

2

Here you go:

$x = array(4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith");

function draw_stars($array){
   foreach($array as $element){
      if(is_int($element)){
        echo str_repeat("*", $element);
      }
      else{
        echo strtolower(str_repeat(substr($element, 0,1), strlen($element)));
      }
      echo "<br>";
  }
}

draw_stars($x);

Output:

****
ttt
*
mmmmmmm
*****
*******
jjjjjjjjjjj
Sign up to request clarification or add additional context in comments.

7 Comments

Oh nice, didn't know about str_repeat
How to add <br> so that it would return on a new line/
@Rodel Garcia You just add echo "<br>"; after if else statement.
@Muhammet I think it's clearer if you echo <br> once after if statement.
question why the letters are caps?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.