ttmt-73 Posted October 8, 2014 Share Posted October 8, 2014 Hi all Is it possible to have a function with two parameters but and then check if one is passed before using it. In this code here I want to remove spaces and change to lowercase. If the $extra parameter is set I want to add that to the end of the string. function className($nametoUse, $extra){ $noSpace = str_replace(' ', '', $nametoUse); $toLower = strtolower($noSpace); if(!empty($extra)){ $classtoUse = $toLower." ".$extra; }else{ $classtoUse = $toLower; } return $classtoUse; } Link to comment https://forums.phpfreaks.com/topic/291500-php-function-use-parameter-if-set/ Share on other sites More sharing options...
Barand Posted October 8, 2014 Share Posted October 8, 2014 Define the function as function className($nametoUse, $extra='' ){ ... } Then the extra parameter is optional, and empty if you do not provide it. Link to comment https://forums.phpfreaks.com/topic/291500-php-function-use-parameter-if-set/#findComment-1493005 Share on other sites More sharing options...
Frank_b Posted October 8, 2014 Share Posted October 8, 2014 instead of an empty value you may also set a default value: function round($number, $decimals = 2 ){ ...} Link to comment https://forums.phpfreaks.com/topic/291500-php-function-use-parameter-if-set/#findComment-1493015 Share on other sites More sharing options...
cyberRobot Posted October 8, 2014 Share Posted October 8, 2014 In addition to the suggestions provided already, there are more options available in the manual: http://php.net/manual/en/functions.arguments.php Link to comment https://forums.phpfreaks.com/topic/291500-php-function-use-parameter-if-set/#findComment-1493019 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.