J L
J L

Reputation: 126

Function With/Without Passing an argument - PHP

Below is a function I created for inserting break lines.

It works fine like this; br(2); //any number, 2 as an example.

However I would like it to work if I typed just br(); it will use 1, but if I specify a number it will use that. Sort of as a default value if none is specified, I've looked throughout google, but can't find the right words to search and find te answer I suppose.

function br($i) {
    $j = 0;
    while ($j <= $i) {
        echo '<br />';
        $j++;
    }
}

Upvotes: 0

Views: 47

Answers (4)

AbraCadaver
AbraCadaver

Reputation: 78994

You want Default Parameters. Maybe just:

function br($i=1) {
    echo str_repeat('<br />', $i);
}

Upvotes: 2

Blah Argh
Blah Argh

Reputation: 302

You can try this:

function br($count = 1)
{
    while($count) {
        echo '<br />';
        $count--;
    }
}

The "$count = 1" part designates $count as an optional parameter. http://php.net/manual/en/functions.arguments.php#functions.arguments.default

Upvotes: 0

mhall
mhall

Reputation: 3701

Add 1 as the default

function br($i = 1) {
    $j = 0;
    while ($j <= $i) {
        echo '<br />';
        $j++;
    }
}

Upvotes: 0

Ingmar Boddington
Ingmar Boddington

Reputation: 3500

You want to use a default value:

function br($i = 1) {
    $j = 0;
    while ($j <= $i) {
        echo '<br />';
        $j++;
    }
}

Reference: PHP Manual - Function arguments

Upvotes: 1

Related Questions