- PHP

How to make PHP Function Argument Optional

Sometimes the same function may or may not take some additional argument depending on where it is used. Fortunately, there is no need to create a second, exactly the same function without an additional parameter. It would be a pointless repetition of your code.

In PHP, we can set a function argument to be optional. To do so, we just need to assign a default value in the given function parameter. This can be some value, an empty string or, for example, FALSE.

<?php

function myFunction($optionalParameter = '') {
  // do something
}

?>

Example:

<?php

function addGuest($guest, $secondPerson = false) {
  echo $guest;

  if($secondPerson !== false) {
    echo ' + ' . $secondPerson; 
  }

  echo '<br>';
}

echo '<b>Guest list:</b><hr>';
addGuest('Juan', 'Pamela');
addGuest('Amy', 'Peter');
addGuest('Jenny');
addGuest('Mark', 'Emma');

Output:

Guest list:
Juan + Pamela
Amy + Peter
Jenny
Mark + Emma