/    Sign up×
Community /Pin to ProfileBookmark

php default arguements

just flicking through the php manual nd have come across default arguements. my question is regarding multiple default arguements. in the following code

“`
function my_function($var, $var2 = “a”, $var3 = “b”){}
“`

how would i provide a non defaut value for var3 without giving anything for var2?

to post a comment
PHP

5 Comments(s)

Copy linkTweet thisAlerts:
@ginerjmApr 03.2020 — How about just skipping it? As in:

my_function($value1, , $value3);
Copy linkTweet thisAlerts:
@cole_pauthorApr 03.2020 — im on my mobile at the moment so i have no way of testing. does that work?
Copy linkTweet thisAlerts:
@ginerjmApr 03.2020 — I"m waiting to hear if it works for you

BTW - it's "arguments".
Copy linkTweet thisAlerts:
@ginerjmApr 03.2020 — Seems that a bit of testing proves my proposal to be false.
Copy linkTweet thisAlerts:
@NogDogApr 03.2020 — Unfortunately, no, you have to supply a second argument in that case if you want to supply the 3rd one. So if you need to support either/or (as opposed to being able to switch the order in the function definition), you'd probably have to do something like:
<i>
</i>function foo($arg1, $arg2=2, $arg3=3)
{
if(!isset($arg2)) {
$arg2 = 2;
}
echo "$arg1, $arg2, $arg3n";
}

Then you'd call it like this if you only want to supply the 3rd argument without the second:
<i>
</i>foo('123', null, '456');

It would be nice if you could just ',,' it, but unfortunately you can't. In CLI mode:
<i>
</i>php &gt; foo(123,,456);

Parse error: syntax error, unexpected ',' in php shell code on line 1
×

Success!

Help @cole_p spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...