AV1611 Posted February 14, 2009 Share Posted February 14, 2009 I have a function I wrote, but to make the point, here's a simple example. Let's say I do function myfunc($a,$b){ echo $a; echo $b; } What I want to do is make $b optional, and if it's not set, for the function to assume a predefined string. In this case it's a percentage that I use in some css later, so I want the string to default to 100 if $b is not used i.e. myfunc($a) but $b to pass if it's myfunc($a,$b) How do I do that? Thanks. Link to comment https://forums.phpfreaks.com/topic/145234-solved-function-question/ Share on other sites More sharing options...
genericnumber1 Posted February 14, 2009 Share Posted February 14, 2009 Easy enough... <?php function myfunc($a,$b = '100'){ echo $a; echo $b; } Link to comment https://forums.phpfreaks.com/topic/145234-solved-function-question/#findComment-762394 Share on other sites More sharing options...
AV1611 Posted February 14, 2009 Author Share Posted February 14, 2009 Easy enough... <?php function myfunc($a,$b = '100'){ echo $a; echo $b; } Thanks, I found that but it didn't make sense until you just did it I also found this but it's more complex than I need in this case, but is a better answer maybe in some cases: $numArgs = func_num_args(); Thanks. Link to comment https://forums.phpfreaks.com/topic/145234-solved-function-question/#findComment-762395 Share on other sites More sharing options...
genericnumber1 Posted February 14, 2009 Share Posted February 14, 2009 Yes, PHP, like some other languages, supports variable number of arguments through the func_num_args and func_get_args functions. Very handy. Link to comment https://forums.phpfreaks.com/topic/145234-solved-function-question/#findComment-762396 Share on other sites More sharing options...
allworknoplay Posted February 14, 2009 Share Posted February 14, 2009 Be careful with these built in functions such as func_num_args(); Because they allow a variety of different inputs so it could be a hassle to trouble issues if your program gets long and complicated. The best way is what GenericNumber posted as his example. Also, functions only accept scalar variables so don't get too carried away... Link to comment https://forums.phpfreaks.com/topic/145234-solved-function-question/#findComment-762409 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.