Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an optional argument in my custom function in PHP?

Tags:

function

php

For example, here's a quick dummy function that sums it up:

function dummy_func($optional)
{
    if (!isset($optional)
    {
        $optional = "World!";
    }
    $output = "Hello " . $optional;
    return $output;
}

However, if I run this, I get an E_WARNING for a missing argument. How can I set it up so it doesn't flag an error?

like image 862
Rob Avatar asked Oct 04 '10 14:10

Rob


2 Answers

Optional arguments need to be given a default value. Instead of checking isset on the argument, just give it the value you want it to have if not given:

function dummy_func($optional = "World!")
{
    $output = "Hello " . $optional;
    return $output;
}

See the page on Function arguments in the manual (particularly the Default argument values section).

like image 198
Daniel Vandersluis Avatar answered Oct 22 '22 16:10

Daniel Vandersluis


You can do that by making $optional argument take default value of "World!":

function dummy_func($optional="World!")
{
    $output = "Hello " . $optional;
    return $output;
}

Now when calling the function if you don't provide any argument, $optional will take the default value but if you pass an argument, $optional will take the value passed.

Example:

echo dummy_func();      // makes use of default value...prints Hello World!
echo dummy_func('foo!'); // makes use of argument passed...prints Hello foo!
like image 9
codaddict Avatar answered Oct 22 '22 16:10

codaddict