CodeIgniter Forums
optional parameters in functions - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: optional parameters in functions (/thread-22375.html)



optional parameters in functions - El Forum - 09-07-2009

[eluser]richzilla[/eluser]
I dont know if this is a general PHP question or wether code igniter implements its own solution,but here goes. My pages have a builder function for the page that takes 2 parameters, the page to be loaded, and and any data that may or may not be needed by the page. Ive done quite a lot of asp.net/C# and i know you can specify a parameter as optional with the ? symbol, but is there a similar solution in php?

cheers


optional parameters in functions - El Forum - 09-07-2009

[eluser]Dam1an[/eluser]
For an optional parameter, you just set it a default value
So:
Code:
function my_function($i_need_this_paramter, $optional_second_parameter = 'a default value') {
  ...
}



optional parameters in functions - El Forum - 09-07-2009

[eluser]jedd[/eluser]
Mind, you don't *need* to mention the second parameter there - CI will happily ignore additional parameters that it doesn't know what to do with anyway. And, also, you don't need to set a default value for any of your parameters. If there's no default, the variable is not set (or set to NULL - I forget which, and it's easy enough for you to test).


optional parameters in functions - El Forum - 09-07-2009

[eluser]InsiteFX[/eluser]
Hi,

Code:
if (empty($variable)
{
   // variable is empty no value
   dothis;
}
else
{
    // variable has a value
    dothis;
}

// Or you can do a single check like this

if ( ! empty($variable)
{
   // variable has a value
   dothis;
}

Enjoy
InsiteFX