Gmz1023
Gmz1023

Reputation: 119

Repeating a string `x` number of times without an if block

Is there any way to repeat a string an arbitrary number of times? I have this code, and I feel like there should be a simpler way of doing it.

    $vitals = parent::userVitals($uid);
    $hearts = round($vitals['health']/25);
    /* with our powers combined! */
    if($hearts == 4)
    {
        $health = "♥♥♥♥";
    }
    elseif($hearts == 3)
    {
        $health = "♥♥♥";

    }
    elseif($hearts == 2)
    {
        $health = "♥♥";
    }
    elseif($hearts == 1)
    {
        $health = "♥";
    }
    return $health;

Upvotes: 0

Views: 97

Answers (2)

Brad
Brad

Reputation: 163272

$health = str_repeat('♥', $hearts);

http://php.net/manual/en/function.str-repeat.php

PHP is filled with random functions like this. No need to reinvent the wheel.

Upvotes: 4

GautamD31
GautamD31

Reputation: 28763

Try with for-loop like

$vitals = parent::userVitals($uid);
$hearts = round($vitals['health']/25);

$health = "";
for( $i=0 ; $i < $hearts ; $i++) {
   $health .= "&hearts;";
}

Upvotes: 3

Related Questions