i

PHP Tutorial

Understanding Arguments Or Parameters

A variable used within the function’s curly parenthesis is known as parameters or arguments. They are basically the placeholders that hold values at runtime. You can use as many arguments or parameters in function as you require. Use a comma to separate the parameters. These parameters accept inputs at runtime when the function is called.

>Default Parameters 

You can also set default values to the parameters in the function. When the user doesn’t provide any input, then these default values are used to the set the argument value in PHP. 

For example:

function age($name, $x=18)

{

           echo “$name is $x years old \n”;

}

age(“Kiara”,22); //Calling function with both parameters

age(“Allen”); //Calling function with default parameter     

?>

Output of the above code will be

Kiara is 22 years old

Allen is 18 years old

>Passing Values to Function

We can pass parameters to functions in two ways using PHP.

  • Pass by value – In this method, the value of parameter gets changed inside the function, and the original value remains unchanged, i.e. a duplicate value is passed to the function.

  • Pass by Reference – In this method, the original value is passed to the function, and the original value gets changed. We pass the address of the value using this method where the value is stored using &.

For example

//Passing parameter by value

function valpass($x)

{

           $x +=10;

           return $x;

}

 

//Passing parameter by reference

function refpass(&$x)

{

           $x +=10;

           return $x;

$y =5;

valpass($n);

echo” Value remains unchanged and is $n
”;

 refpass($n);

echo” Value changed by function and is $n”;

?>

The output of the above code will be:

Value remains unchanged and is 5

Value changed by function and is 15

So, the variable value is not changed when we pass by value, but the original value gets changed when we pass by reference.