How to Create PHP Optional Parameters [Tutorial]

PHP Optional Parameters

Well, you probably have heard of optional parameters. It’s a concept that exists in almost every programming language. Today we will be discussing optional parameters in PHP. If you study the PHP standard documentation, you probably have seen many functions with optional parameters. They usually follow the following format.

string funtionName( string $var1 [, int $var2 = 5, string $var3=”hello world” ] )Code language: PHP (php)

Parameters inside the [] are optional parameters. You can see that values have been assigned to optional parameters. They are called default values.

What it does is, if you don’t assign a value to an optional parameter, the default value will be assigned to that optional parameter.

Let’s study one of them. We will try a very common function. You probably have used str_split function before. It has the following method signature.

str_split ( string $string [, int $split_length = 1 ] ) : arrayCode language: PHP (php)

It is used to split a string into an array. It takes two arguments. First is the string to be split which is a required parameter.

The second one is the maximum length of a chunk after the split. You can see the default value of split_length is 1. That means the string is broken into an array of strings which have a length of 1.

Let’s see how this function behaves with a practical example.

$str = "Hello World";
$arr1 = str_split($str);
$arr2 = str_split($str, 4);
print_r($arr1);
print_r($arr2);Code language: PHP (php)

Output

Array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => W [7] => o [8] => r [9] => l [10] => d ) 
Array ( [0] => Hell [1] => o Wo [2] => rld )Code language: PHP (php)

In this example, Hello World is assigned to $str. Then we have split this string into an array using the str_split function. First, we didn’t give a value to the optional parameter.

Therefore, 1 is assigned to the split_length parameter resulting in the following output:

array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => W [7] => o [8] => r [9] => l [10] => d )Code language: PHP (php)

The second time we assigned 4 to the split_length attribute.

Therefore, we got the following output:

Array ( [0] => Hell [1] => o Wo [2] => rld )Code language: PHP (php)

How do you create a function with optional parameters?

Probably you are wondering now that how do you create functions with optional parameters.

If you closely notice our previous example you would have able to understand it by now.

There was one similarity in every example. Optional parameters were given a default value.

Yes, that’s all you have to do. Give a default value to a parameter in your function to make it an optional parameter.

Let’s try this with a custom function.

<!--?php
function add($a,$b=5){
	echo $a+$b."<br-->";
}
add(10);
add(10,20);
?>Code language: PHP (php)

This is a very basic function. It adds two numbers and prints it. You can invoke this function using either of add(10), add(10,20) methods.

Because the second parameter of add function which is $b is an optional parameter. You will get the following output for this when this code is executed.

15
30Code language: PHP (php)

First output was created by adding 10 to 5 which is the default value of $b. Second output was created by adding both parameters which were passed to the function.

Next, we will go to a more complicated function.

function calculator($num1=5,$num2=5,$op="+"){
   switch ($op) {
    case "+":
        echo $num1 + $num2."<br>";
        break;
    case "-":
        echo $num1 - $num2."<br>";
        break;
    case "*":
        echo $num1 * $num2."<br>";
        break;
   case "/":
        echo $num1 / $num2."<br>";
        break;
    default:
        echo "Incorrect Operation <br>";
   }
}

calculator();
calculator(10);
calculator(15,12);
calculator(15,3,"*");Code language: PHP (php)

Output

10
15
27
45Code language: PHP (php)

Check the above code which tries to create a simple calculator.

All three parameters are optional.

The logic of the code is pretty simple to understand. Therefore I am not going to discuss it.

The important point is you can invoke the calculator method with any of the following methods.

'calculator()'
'calculator(10)'
'calculator(15,12)'
'calculator(15,3,"*")'Code language: PHP (php)

But there is an interesting question to ask.

What if you want to skip the first optional parameter and then pass values to other optional parameters?

This is not possible with PHP. You can’t skip optional parameters unless they are at the end of the parameter list.

The only option left to you is to assign the default value manually like this

`calculator(5,3,"-")`Code language: PHP (php)

Here $num1 is given the default value. Then we pass values to $num2 and $op.

When do you need optional parameters?

Let’s discuss when you need to define a function with optional parameters. Let’s say you have a function that uses the same value as an argument very often.

It would be easier if you can define the function with that value assigned as a default value for that parameter.

This makes things easier when you or someone else tries to use it.

If we look at the two examples that we created in the above section, both of them don’t explain why exactly optional parameters should be used.

For example, if we take add method, there is no real point of giving 5 as the default value of $b. There is no special probability for $b to be five. Even in the second case, there is no point of operation to be “+”.

If you use optional parameters where it’s not necessary, this could create side effects.

For example, the programmer could forget to give the correct parameter value when invoking the method as there won’t be any compiler error. Thus the code will create a logical error which is more difficult to trace than a compile error.

Let’s do an example to understand when it’s really necessary to use optional parameters. Without trying to use an entirely new example, we will just extend our previous example.

Let’s say you want to write an add method. It is obvious that most users want to have the answer in decimal.

But, suppose that you want to extend this function to get an answer in octal and binary as well.

Then, it is a good practice to keep decimal as the default format of the answer while allowing users to give another number system as an optional parameter.

<!--?php
function add($a,$b, $format="D"){
   if($format=="O")
      echo base_convert($a+$b,10,8)."<br-->";
   elseif($format=="B")
      echo base_convert($a+$b,10,2)."<br>";
   else
      echo $a+$b."<br>";
}

add(10,20);
add(10,20,"O");
add(10,20,"B");Code language: PHP (php)

Output

30
36
11110Code language: PHP (php)

If you want the answer in Octal, pass “O” as an argument to add method. If you want the answer in Binary, pass “B” as an argument. If you don’t pass any value for the third parameter, the answer will come in Decimal.

Conclusion

We discuss optional parameters in PHP functions. We looked at examples from the PHP standard library. Then we create our own custom function with optional parameters. Then we learned that you can’t skip optional parameters in PHP. finally, I told you how to use optional parameters effectively.

    by
  • A Z Hasnain Kabir

    I am an aspiring software engineer currently studying at the Islamic University of Technology in Bangladesh. My technical skills include Python automation, data science, machine learning, PHP, cURL and more. With a passion for creating innovative solutions, I am dedicated to mastering the art of software engineering and contributing to the technological advancements of tomorrow.

Leave a Comment