Default value arguments in PHP

Functions can be inbuilt or user-defined, inbuilt functions are ready made ones, these include array(), var_dump(), array_search(), there are many…

When we create functions, they are termed as user- defined functions. In user defined functions we pass some values in it those values are passed as formal parameters inside the function. Let me show you an example-

One thing to note in above code is- we can call our function anywhere in program irrespective of its position of function definition. In program, I have called calci() 2 times and it is valid in PHP.

The variables $a,$b,$c,$d are formal parameters and their scope is limited within function only. They do not exist outside function. While the values passed during calling of function 4,6,8,82 are actual parameters.

Imagine if $a, $b, $c, $d are prices of four items and what if price of $d remains same every time. We can do it in following way-

In above code, I have set $d as default value argument i.e. by default its value will be 82. In case you want to pass your own value, you can do so. In that case 82 will be over-written by your value.

What happens is – the values 4,6,8,82 goes to $a, $b, $c, $d respectively. When we make $d as default argument, the values 4,6,8 goes to remaining three variables.

Suppose we want to make $a and $d both as default value arguments, then ? We all will quickly do this-

function calci($a=4, $b, $c, $d=82)

and in function calling – calci(6,8);

But no, this is absolutely wrong . Because how will PHP know that it has to copy the value 6 to $b. PHP will copy 6 to $a and 8 to $b and then no value for $c, and no value for $d also. But remember that $d is in last and it has its default value, so no matter if $d gets value or not, it has it’s own value. But the problem is for $c. So what to do now? Relax and look at the following code-

What I have done is- I have written all default arguments ($a ,$d) at last. Now, the value 6 is copied to $b, the value 8 is copied to $c and no value is copied to $a and $d. But this is not an error here, because both of these have their default arguments with them.

So the conclusion is always keep default value arguments at the end of the list.

I hope this is clear, if not, then no problem comment your doubt here and it will be resolved and you will feel SUPER GOOD.

Have a ERROR-FREE coding…