没有if块重复字符串`x`次

时间:2013-08-03 05:04:54

标签: php

有没有办法重复任意次数的字符串?我有这个代码,我觉得应该有一个更简单的方法。

    $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;

2 个答案:

答案 0 :(得分:4)

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

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

PHP充满了像这样的随机函数。无需重新发明轮子。

答案 1 :(得分:3)

尝试for-loop喜欢

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

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