Read Time:1 Minute, 36 Second
PHP- Function arguments

Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. The arguments are evaluated from left to right.
PHP supports passing arguments by value (the default), passing by reference, and default argument values. Variable-length argument lists and Named Arguments are also supported.
Example #1 Function with one argument
<?php
function familyName($fname) {
echo "$fname Kumar.<br>";
}
familyName("Gaurav");
familyName("Cabdi");
familyName("Adil");
familyName("Prateek");
familyName("John");
?>
Example #2 Function with two arguments
<?php
function familyName($fname, $year) {
echo "$fname Kumar. Born in $year <br>";
}
familyName("Gaurav", "1998");
familyName("Sagar", "2003");
familyName("Shubham", "1999");
?>
Example #3 Passing arrays to functions
<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
$arr=array(25,63);
takes_array($arr);
?>
Output:
25 + 63 = 88
Example #4 Function Argument List with trailing Comma
<?php
function takes_many_args(
$first_arg,
$second_arg,
$a_very_long_argument_name,
$arg_with_default = 5,
$again = 'a default string', // This trailing comma was not permitted before 8.0.0.
)
{
// ...
}
?>
Example #5 Use of default parameters in functions
<?php
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>
Output:
Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.
Example #6 Passing optional arguments after mandatory arguments
<?php
function foo($a = [], $b) {} // Default not used; deprecated as of PHP 8.0.0
function foo($a, $b) {} // Functionally equivalent, no deprecation notice
function bar(A $a = null, $b) {} // Still allowed; $a is required but nullable
function bar(?A $a, $b) {} // Recommended
?>
Example #7 Named argument
<?php
// Using positional arguments:
array_fill(0, 100, 50);
// Using named arguments:
array_fill(start_index: 0, count: 100, value: 50);
//same as
array_fill(value: 50, count: 100, start_index: 0);
?>
Average Rating