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
https://forums.phpfreaks.com/topic/66993-optional-arguments-in-functions/
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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.