0

I'm teaching myself PHP through a book and to make this easier I made myself a function to save myself having to write echo "<br/>"; a million times. My function works fine but after accidentally leaving out a parameter and getting an error I tried to make it so that if I left the function empty it would simply add one <br/> but I can't seem to get it to work.

Here is my code after my last attempt (which was to try case NULL: echo "<br/>";):

function br($break){
    switch ($break){
        case 1:
            echo "<br/>";
            break;
        case 2:
            echo "<br/><br/>";
            break;
        case 3:
            echo "<br/><br/><br/>";
            break;
        case 4:
            echo "<br/><br/><br/><br/>";
            break;
        case 5:
            echo "<br/><br/><br/><br/><br/>";
            break;
        case NULL:
            echo "<br/>";
    }

}

Any ideas? Thanks guys!

P.s. Sorry if this is a really silly question, I only started learning PHP on Monday and my programming experience is somewhat limited :)

4

3 回答 3

4

试试这样:

function br($break = 1){

}

顺便说一句,对于您的情况,您实际上可以使用:

echo str_repeat('<br />', 5);

这将创建 5 个 br,请看这里: http: //php.net/str_repeat
另外,当您对某事有疑问时,第一次检查 php.net 文档,可能有一个功能可以满足您的需求。

于 2013-04-18T11:10:13.460 回答
1

如果 yopu 默认想要 1 br,你可以这样做:

function br($break = 1){

}
于 2013-04-18T11:11:09.400 回答
0

根本不使用 switch 可能更容易,而是做这样的事情:

function br($break = null)
{
    if(!is_null($break)) {
        echo str_repeat('<br />', (int) $break);
    } else {
        echo '<br />';
    }
}

(未测试)

于 2013-04-18T11:21:00.127 回答