Simple: passing null value to function


function display_details($name, $department="sales", $sex="male") {
   return "You are {$name} from {$department} and you are {$sex}";
}

I need to use the default value for $department, but none of the below work. How do I do it?

echo $display_details(“Sally”, NULL, “female”); // sets $department as empty/blank

echo $display_details(“Sally”, “”, “female”); // sets $department as empty/blank

echo $display_details(“Sally”, , “female”); // PHP error

You can’t.

You can reorder the params though, but if you know what the default value is, why not simply pass it in again?

Try a different tack:


function display_details($name, $department=NULL, $sex=NULL) {

if( empty($department) ) $department = "sales";
if( empty($sex) ) $sex = "male";

   return "You are {$name} from {$department} and you are {$sex}";
}

Does that work? (not in my usual test environment, sorry)

Edit: haha, beaten to it. But I’ll keep it as this and what the poster above me said, is what you should be doing, for all incoming vars. You should check the incoming vars to see that they are valid and have values, and set a default that way. Defaulting like this is fine but shouldn’t be relied on for validation.


function display_details($name, $department="sales", $sex="male") 
{
   if(empty($department))
   {
      $department = "sales";
   }

   return "You are {$name} from {$department} and you are {$sex}";
}

echo $display_details("Sally", "", "female");


That will set department to sales if you pass ‘’ in the place of department.

Basically your when you do this:
echo $display_details(“Sally”, “”, “female”);

You are passing something in, an empty value, so the default isn’t collected, so simply set it in the function by checking it, which you should do with all incoming data anyway.

Of course if you re-order the variables so department is at the end then you can just exclude it from the function call but it’s not great to do that as you can wind up with problems later down the line if you need to add to the function and end up altering it in a load of places.

I would’t say “you can’t”. Try to modify your function like this.

function display_details($name, $department=null, $sex=“male”) {
$department = ($department) ? $department : “sales”;

return “You are {$name} from {$department} and you are {$sex}”;
}