Jump to content

Optional arguments in functions


trink

Recommended Posts

In a function, how would I make a specific argument optional?

 

Say I had something like this:

function myfunction($a,$b,$c,$d){
if(!$d){
$d=1;
}
return $a.$b.$c.$d;
}

Thats basically what I'm trying to do with my function, and its not working.  It returns the correct value, but I have to supress the error that it returns about not having a 4th argument with a @.  So it ends up looking like @myfunction(1,2,3).  I don't mind using the @ but I'd like to make the fourth argument optional.

 

I'd appreciate any help on this topic.

Link to comment
Share on other sites

You just have to assign the optional arguments a default value, that makes it optional.

 

<?php

function myfunction($a,$b,$c,$d=1){
   return $a.$b.$c.$d;
}

?>

 

So if you don't put anything for $d, it will automatically become "1" as default. If you don't want it to be anything, just put NULL in place of the 1.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.