user5072259
user5072259

Reputation:

PHP code to get the 1st string of each array value

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?

Upvotes: 1

Views: 63

Answers (1)

Muhammet
Muhammet

Reputation: 3308

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

Upvotes: 2

Related Questions