Category: Functions

  • Returning Values

    A PHP function can have an optional return statement as the last statement in its function body. Most of the built-in functions in PHP return a certain value. For example the strlen() function returns the length of a string. Similarly, a user defined function can also return a certain value.

    A function is an independent, complete and reusable block of statements. When called, it performs a certain task and sends the program control back to position from where it was called even if return statement is not used. The return statement allows it to take a value, along with the control, back to the calling environment.

    functionfoo($arg_1,$arg_2){
       statements;return$retval;}

    A function may return any type of data, including scalar variables, arrays and objects. A return keyword without any expression in front of it returns null, and is equivalent to a function not having a return value at all.

    The value returned by a function can be stored in a variable, can be put in an expression, or, if appearing inside print or echo, is displayed in the output.

    $res=foo($x,$y);

    It allows the returned value of a function to be used further in the program.

    Example

    Let us modify the addition() function in the previous chapter to include a return statement to return the result of addition.

    <?php
       function addition($first, $second) {
    
      $result = $first+$second;
      return $result;
    } $x=10; $y=20; $z = addition($x, $y); echo "First number: $x Second number: $y Addition: $z". PHP_EOL; ?>

    Output

    It will produce the following output −

    First number: 10 Second number: 20 Addition: 30
    

    A function in PHP may have any number of arguments, but can return only one value. The function goes back to the calling environment as soon as it comes across a return statement for the first time, abandoning the rest of statements in the function body.

    Example

    If you try to include more than one values in the return statement, a PHP parse error is encountered as below −

    <?php
       function raiseto($x) {
    
      $sqr =  $x**2;
      $cub =  $x**3;
      return $sqr, $cub;
    } $a = 5; $val = raiseto($a); ?>

    Output

    It will produce the following output −

    PHP Parse error: syntax error, unexpected token ",", expecting ";" 
    

    Conditional Return

    You can have multiple return statements executed under different conditional statements.

    Example

    In the following program, the raiseto() function returns either the square or the cube of a number of the index argument, that is either 2 or 3, respectively.

    <?php
       function raiseto($x, $i) {
    
      if ($i == 2) {
         return $x**2;
      } elseif ($i==3) {
         return $x**3;
      }
    } $a = 5; $b = 2; $val = raiseto($a, $b); echo "$a raised to $b = $val" . PHP_EOL; $x = 7; $y = 3; echo "$x raised to $y = " . raiseto($x, $y) . PHP_EOL; ?>

    Output

    It will produce the following output −

    5 raised to 2 = 25
    7 raised to 3 = 343
    

    Return Multiple Values as Array

    The function in PHP is capable of returning only a single value. However, that single value can be an array of more than one values. We can take the advantage of this feature to return the square as well as the cube of a number at once.

    Example

    Take a look at the following example −

    <?php
       function raiseto($x){
    
      $sqr =  $x**2;
      $cub =  $x**3;
      $ret = ["sqr" =&gt; $sqr, "cub" =&gt; $cub];
      return $ret;
    } $a = 5; $val = raiseto($a); echo "Square of $a: " . $val["sqr"] . PHP_EOL; echo "Cube of $a: " . $val["cub"] . PHP_EOL; ?>

    Output

    It will produce the following output −

    Square of 5: 25
    Cube of 5: 125
  • Variable Arguments

    In PHP, it is possible to write a function capable of accepting a list of arguments with variable number of elements. To declare a variable argument list, the name of the argument is prepended by the “…” (three dots) symbol. The values passed are collected into an array with the argument’s name.

    Here is the syntax we can use for defining the variable arguments −

    functionmyfunction(...$arg){
       Statement1;
       Statement2;}

    Call the Function with Variable Arguments

    To call such a function, put any number of comma-separated values in the parenthesis.

    myfunction(v1, v2, v3,..., vn);

    The formal argument declared in the function is an array of all the values passed. We van use any of the appropriate built_in array functions to perform the process.

    Example

    In the following example, the user defined function myfunction() is capable of receiving variable number of values and finds their average.

    <?php  
       function  myfunction(...$numbers) {
    
      $avg = array_sum($numbers)/count($numbers);
      return $avg;
    } $avg = myfunction(5, 12, 9, 23, 8); echo "average = $avg"; ?>

    Output

    It will produce the following output −

    average = 11.4
    

    Try changing the size of the passed array and run the program again.

    You can use a foreach loop to traverse the array inside the function. The function may have any positional arguments before the variable length argument. From the received values, the positional arguments will be populated first, leaving others to be copied to the array.

    Example

    <?php
       function myfunction($x, ...$numbers) {
    
      echo "First number: $x" . PHP_EOL;
      echo "Remaining numbers: ";
      foreach ($numbers as $n) {
         echo "$n  ";
      }
    } myfunction(5, 12, 9, 23, 8, 41); ?>

    Output

    It will generate the following output −

    First number: 5
    Remaining numbers: 12  9  23  8  41
    

    Variadic Functions

    It is possible to process a variable number of arguments to a function, even without the “…” syntax. PHP has built_in functions like func_num_args(), func_get_arg() and func_get_args(), which can be used with similar result.

    • func_num_args() − Returns the number of arguments passed to the function.
    • func_get_arg() − Returns an item from the argument list
    • func_get_args() − Returns an array comprising a function’s argument list

    Example

    The above example of variable arguments can be rewritten with these functions as below −

    <?php
       function myfunction() {
    
      $sum = 0;
      foreach (func_get_args() as $n) {
         $sum += $n;
      }
      return $sum;
    } echo myfunction(5, 12, 9, 23, 8, 41); ?>

    Output

    It will produce the following output −

    98
    

    Example

    This program prints all the numbers passed to the function −

    <?php
       function myfunction() {
    
      $len = func_num_args();
      echo "Numbers : ";
      $i=0;
      for ($i=0; $i&lt;$len; $i++)
      echo func_get_arg($i) . " ";
    } myfunction(5, 12, 9, 23, 8, 41); ?>

    Output

    It will produce the following output −

    Numbers : 5 12 9 23 8 41
  • Named Arguments

    The feature of Named Arguments has been introduced in PHP with the version 8.0. It is an extension of the existing mechanism of passing positional arguments to a function while calling.

    By default, values of passed arguments are copied to the corresponding formal arguments at the same position. This feature of named arguments in PHP makes it possible to pass the value based on the parameter name instead of the position.

    Example with Positional Arguments

    If we have a function defined as follows −

    functionmyfunction($x,$y){
       statement1;
       statement2;...}

    and it is called as −

    myfunction(10,20);

    In this case, the values are passed to the variables “x” and “y” in the order of declaration. It means, the first value to the first argument, second value to second argument and so on. The variables “x” and “y” are positional arguments.

    To pass the values by named arguments, specify the parameter name to which argument the value is to be passed. The name of the parameter is the name of formal argument without the “$” symbol. The value to be passed is put in front of the “:” symbol.

    myfunction(x:10,y:20);

    Example with Named Arguments

    Here is the code that demonstrates how you can use named arguments in PHP −

    <?php  
       function  myfunction($x, $y) {
    
      echo "x = $x  y = $y";
    } myfunction(x:10, y:20); ?>

    Output

    It will produce the following output −

    x = 10  y = 20
    

    Using named arguments makes it possible to pass the values in any order, and not necessarily in the same order in which the arguments are declared in the function definition. We can call myfunction() as shown below and it will produce the same result.

    myfunction(y:20,x:10);

    With this feature, the arguments become order-independent and self-documenting. It also makes it possible to skip the arguments with default values arbitrarily.

    Combining Named Arguments with Positional Arguments

    Named arguments can be combined with positional arguments, with the condition that, the named arguments must come after the positional arguments.

    <?php  
       function  myfunction($x, $y, $z) {
    
      echo "x = $x  y = $y  z = $z";
    } myfunction(10, z:20, y:30); ?>

    Output

    It will generate the following result −

    x = 10  y = 30  z = 20
    

    However, if you try to treat $z as a positional argument,

    myfunction(x:10,y:20,30);

    In this case, PHP will encounter the following error −

    PHP Fatal error:  Cannot use positional argument after 
    named argument in hello.php on line 7
    

    Passing Named Arguments from an Array

    PHP 8.1.0 also introduced another feature that allows using named argument after unpacking the arguments. Instead of providing values to each argument individually, the values in an array an be unpacked into the corresponding arguments, using “…” (three dots) before the array.

    <?php  
       function  myfunction($x, $y, $z=30) {
    
      echo "x = $x  y = $y  z = $z";
    } myfunction(...[10, 20], z:30); ?>

    Output

    It will produce the following output −

    x = 10  y = 20  z = 30
    

    Note that passing the same parameter multiple times results in an exception as follows −

    myfunction(x:10,z:20,x:20);

    Error −

    PHP Fatal error:  Uncaught Error: Named parameter $x 
    overwrites previous argument in hello.php:7
    

    Positional Arguments vs Named Arguments

    Positional arguments are passed in the same order as the function parameters. In this the position or order matters. See the example for positional argument −

    <?php  
       def greet(name, age):
    
      print(f"Hello, my name is {name} and I am {age} years old.")
    greet("Amit", 25) ?>

    Output

    It will produce the following output −

    Hello, my name is Amit and I am 25 years old.
    

    While the arguments passed with parameter names are called Named arguments. The position does not matter because you name the arguments.

    <?php  
       greet(name="Amit", age=25)
    ?>

    Output

    It will produce the following output −

    Hello, my name is Amit and I am 25 years old.
    

    Or change the order −

    <?php  
       greet(age=25, name="Amit")
    ?>

    The output for the above code will be the same. So it proves if we change the order of arguments it does not affect the output of the program.

    Passing Arguments by Reference

    Normally, when you pass a variable to a function, PHP makes a copy of it. If you change a variable inside the function, the original value outside the function remains unchanged. But when you pass a reference (with the & symbol), the function uses the original variable rather than a copy. So, if the function changes the variable, it will be reflected outside of the function!

    <?php  
       function updateString(&$str) 
       {
    
      $str .= " updated";
    } $text = "This is just a test string"; updateString($text); echo $text; ?>

    Output

    It will generate the below output −

    This is just a test string updated
    

    It’s useful when you want to update a variable within a function but maintain the change outside of the function. But you have be careful because falsely changing the variable can lead to unexpected outcomes in your program.

  • Default Arguments

    Like most of the languages that support imperative programming, a function in PHP may have one or more arguments that have a default value. As a result, such a function may be called without passing any value to it. If there is no value meant to be passed, the function will take its default value for processing. If the function call does provide a value, the default value will be overridden.

    Function Definition with Default Values

    Here is the way you can define a function with default values −

    functionfun($arg1= val1,$arg2= val2){
       Statements;}

    Different Ways to Call the Function

    The above function can be called in different ways −

    fun();# Function will use defaults for both argumentsfun($x);# Function passes $x to arg1 and uses default for arg2fun($x,$y);# Both arguments use the values passed

    Example 1

    Here we define a function called greeting() with two arguments, both having string as their default values. We call it by passing one string, two strings and without any argument.

    <?php  
       function  greeting($arg1="Hello", $arg2="world") {
    
      echo $arg1 . " ". $arg2 . PHP_EOL;
    } greeting(); greeting("Thank you"); greeting("Welcome", "back"); greeting("PHP"); ?>

    Output

    It will produce the following output −

    Hello world
    Thank you world
    Welcome back
    PHP world
    

    Example 2

    You can define a function with only some of the arguments with default value, and the others to which the value must be passed.

    <?php  
       function  greeting($arg1, $arg2="World") {
    
      echo $arg1 . " ". $arg2 . PHP_EOL;
    } # greeting(); ## This will raise ArgumentCountError greeting("Thank you"); greeting("Welcome", "back"); ?>

    Output

    It will produce the below result −

    Thank you World
    Welcome back
    

    The first call (without argument) raises ArgumentCountError because you must pass value for the first argument. If only one value is passed, it will be used by the first argument in the list.

    However, if you declare arguments with default before arguments without defaults, such function can be only called if values for both are passed. You cannot have a situation where the first argument uses the default, and the second using the passed value.

    The greeting() function now has $arg1 with default and $arg2 without any default value.

    functiongreeting($arg1="Hello",$arg2){echo$arg1." ".$arg2.PHP_EOL;}

    If you pass a string “PHP” −

    greeting("PHP");

    with the intension to print the result as “Hello PHP”, the following error message will be displayed.

    PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function 
    greeting(), 1 passed in hello.php on line 10 and exactly 2 expected
    

    Example 3

    Let’s define a function percent() that calculates the percentage of marks in three subjects.

    Assuming that the marks in each subject are out of 100, the $total argument in the function definition is given a default value as 300.

    <?php
       function  percent($p, $c, $m, $ttl=300) {
    
      $per = ($p+$c+$m)*100/$ttl;
      echo "Marks obtained: \n";
      echo "Physics = $p Chemistry = $c Maths = $m \n";
      echo "Percentage = $per \n";
    } percent(50, 60, 70); ?>

    Output

    It will generate the following result −

    Marks obtained: 
    Physics = 50 Chemistry = 60 Maths = 70 
    Percentage = 60
    

    However, if the maximum marks in each subject is 50, then you must pass the fourth value to the function, otherwise the percentage will be calculated out of 300 instead of 150.

    <?php
       function  percent($p, $c, $m, $ttl=300) {
    
      $per = ($p+$c+$m)*100/$ttl;
      echo "Marks obtained: \n";
      echo "Physics = $p Chemistry = $c Maths = $m \n";
      echo "Percentage = $per \n";
    } percent(30, 35, 40, 150); ?>

    Output

    It will produce the following output −

    Marks obtained: 
    Physics = 30 Chemistry = 35 Maths = 40 
    Percentage = 70
  • Call by Reference

    PHP uses the “call by value” mechanism, by default, for passing arguments to a function. If the arguments within the function are changed, the changes do not reflect outside of the function. To allow a function to modify its arguments, the “call by reference” mechanism must be used.

    In PHP, a reference variable acts as an “alias” to the original or host variable so that both of them can read and write a single value. In other words, variables of two different names can access to the same value and they behave as if they are the same variable.

    The following PHP script will help in understanding what references are. Here, $var is a normal string variable. We declare $var1 as a reference to $var, append “&” symbol to the latter.

    $var="Hello";$var1=&$var;

    When we say that $var1 is an alias or reference of $var, it means any change in its value will also change the value of $var, and vice versa.

    Example of Call by Reference

    The following another example, which demonstrates how “call by reference” works in PHP −

    <?php  
       $var = "Hello";
       $var1 = &$var;
    
       $var1 = "Hello World";
       echo "var=$var var1=$var1" . PHP_EOL;
    
       $var = "How are you?";
       echo "var=$var var1=$var1" . PHP_EOL;
    ?>

    Output

    It will generate the following output −

    var=Hello World var1=Hello World
    var=How are you? var1=How are you?
    

    Calling a PHP Function by Reference

    To call a function by reference, you need to declare the formal arguments with name prefixed by “&” symbol.

    functioncallref(&$arg1,&$arg2){
       Statements;}

    The call to the function is just as in “call by value” method.

    callref($x,$y);

    When the function is invoked, $arg1 becomes a reference to $x and $arg2 becomes a reference to $y.

    If, inside the function body, the value of $arg1 or $arg2 (or both) changes, it also causes the values of $x and $y to change.

    Example

    Let us have a look at the following example −

    <?php  
       function  change_name(&$nm) {
    
      echo "Initially the name is $nm" . PHP_EOL;
      $nm = $nm."_new";
      echo "This function changes the name to $nm" . PHP_EOL;
    } $name = "John"; echo "My name is $name" . PHP_EOL; change_name($name); echo "My name now is $name" . PHP_EOL; ?>

    The variable $name is passed to the function change_name(). A reference variable &$nm becomes its reference variable. Any change in $nm is reflected in $name outside the function.

    Output

    It will produce the below output −

    My name is John
    Initially the name is John
    This function changes the name to John_new
    My name now is John_new
    

    Swapping Two Variables

    In the following PHP code, we call a function by passing the arguments by value. The function attempts to swap their values.

    Inside the function, their values are changed, but this swap doesnt reflect in the actual arguments after the execution of the function.

    When the same function is called by passing the arguments by reference, the swap effect is reflected in the actual arguments as well.

    <?php  
       function  swap_value($a, $b) {
    
      echo "Initial values a = $a b = $b \n";
      $c = $a; $a = $b; $b = $c;
      echo "Swapped values a = $a b = $b \n";
    } $x = 10; $y =20; echo "Actual arguments x = $x y = $y \n\n"; swap_value($x, $y); echo "Actual arguments do not change after the function: \n"; echo "x = $x y = $y \n\n"; function swap_ref(&$a, &$b) {
      echo "Initial values a = $a b = $b \n";
      $c = $a; $a = $b; $b = $c;
      echo "Swapped values a = $a b = $b \n";
    } swap_ref($x, $y); echo "Actual arguments get changed after the function: \n"; echo "x = $x y = $y"; ?>

    Output

    It will produce the following output −

    Actual arguments x = 10 y = 20 
    
    Initial values a = 10 b = 20 
    Swapped values a = 20 b = 10 
    Actual arguments do not change after the function: 
    x = 10 y = 20 
    
    Initial values a = 10 b = 20 
    Swapped values a = 20 b = 10 
    Actual arguments get changed after the function: 
    x = 20 y = 10
    

    Return by Reference

    Just as a function in PHP can accept arguments by reference, it can also return a reference. To define a function that returns a reference, prefix the name of the function by “&” symbol.

    Example

    The following code shows the example of a function returning a reference. It returns $x, which is a local static variable inside myfunction(). Since “&” symbol is prepended to it, $a (the variable that stores the return value) becomes a reference to &x. As a result, any change in $a will also change the value of $x.

    <?php
       function &myfunction(){
    
      static $x=10;
      echo "x Inside function: $x \n";
      return $x;
    } $a = &myfunction(); echo "Returned by Reference: $a \n"; $a=$a+10; $a = &myfunction(); ?>

    Output

    It will produce the following outcome −

    x Inside function: 10 
    Returned by Reference: 10 
    x Inside function: 20
    
  • Call by Value

    By default, PHP uses the “call by value” mechanism for passing arguments to a function. When a function is called, the values of actual arguments are copied to the formal arguments of the function’s definition.

    During the execution of the function body, if there is any change in the value of any of the formal arguments, it is not reflected in the actual arguments.

    Types of Arguments in PHP Functions

    Here are the two types of arguments used in PHP functions −

    • Actual Arguments − The arguments that are passed in a function call.
    • Formal Arguments − The arguments that are declared in a function definition.

    Syntax

    Here is the way you can define actual and formal arguments in PHP:

    <?php 
       // $name is a formal argument
       function greet($name) {  
    
    echo "Hello, $name!";
    } // Rahul is an actual argument greet("Rahul"); ?>

    Demonstrating Call by Value

    Let us consider the function used in the code below −

    <?php  
       function change_name($nm) {
    
      echo "Initially the name is $nm \n";
      $nm = $nm."_new";
      echo "This function changes the name to $nm \n";
    } $name = "John"; echo "My name is $name \n"; change_name($name); echo "My name is still $name"; ?>

    Output

    It will produce the following result −

    My name is John
    Initially the name is John
    This function changes the name to John_new
    My name is still John
    

    In this example, the change_name() function appends _new to the string argument passed to it. However, the value of the variable that was passed to it remains unchanged after the function’s execution.

    Formal arguments, in fact, behave as local variables for the function. Such a variable is accessible only inside the scope in which it is initialized. For a function, its body marked by the curly brackets “{ }” is its scope. Any variable inside this scope is not available for the code outside it. Hence, manipulation of any local variable has no effect on the world outside.

    The “call by value” method is suitable for a function that uses the values passed to it. It performs certain computation and returns the result without having to change the value of parameters passed to it.

    Note − Any function that performs a formula-type computation is an example of call by value.

    Example 1

    Take a look at the following example −

    <?php
       function addFunction($num1, $num2) {
    
      $sum = $num1 + $num2;
      return $sum;
    } $x = 10; $y = 20; $num = addFunction($x, $y); echo "Sum of the two numbers is : $num"; ?>

    Output

    It will generate the following output −

    Sum of the two numbers is : 30  
    

    Example 2

    Here is another example of calling a function by passing the argument by value. The function increments the received number by 1, but that doesn’t affect the variable passed to it.

    <?php
       function increment($num) {
    
      echo "The initial value: $num \n";
      $num++;
      echo "This function increments the number by 1 to $num \n";
    } $x = 10; increment($x); echo "Number has not changed: $x"; ?>

    Output

    It will produce the following outcome −

    The initial value: 10
    This function increments the number by 1 to 11
    Number has not changed: 10
    

    Example 3

    In the below example we will be incrementing a value and we will not change the original variable.

    <?php
       function increment($num) {
    
      echo "The initial value: $num \n";
      $num++;
      echo "This function increments the number by 1 to $num \n";
    } $x = 10; increment($x); echo "Number has not changed: $x"; ?>

    Output

    It will generate the following outcome −

    The initial value: 10 
    This function increments the number by 1 to 11 
    Number has not changed: 10
    

    String Manipulation in Call by Value

    In php, we can also manipulate strings using call by value. In our example we will append a string by passing a value in the argument.

    <?php
       function appendString($str) {
    
      $str .= " World!";
      echo "Inside function: $str\n";
    } $text = "Hello"; appendString($text); // Original string remains unchanged echo "Outside function: $text"; ?>

    Output

    It will generate the following outcome −

    Inside function: Hello World!
    Outside function: Hello
    

    PHP also supports passing the reference of variables to the function while calling. We shall discuss it in the next chapter.

  • Function Parameters

    Function Parameters in PHP

    A function in PHP may be defined to accept one or more parameters. Function parameters are a comma-separated list of expressions inside the parenthesis in front of the function name while defining a function. A parameter may be of any scalar type (number, string or Boolean), an array, an object, or even another function.

    Syntax

    Here is the syntax for defining parameters in PHP functions −

    functionfoo($arg_1,$arg_2,$arg_n){
       statements;return$retval;}

    The arguments act as the variables to be processed inside the function body. Hence, they follow the same naming conventions as any normal variable, i.e., they should start with “$” and can contain alphabets, digits and underscore.

    Note − There is no restriction on how many parameters can be defined.

    Functions Call with Parameters

    When a parameterized function needs to be called, you have to make sure that the same number of values as in the number of arguments in function’s definition, are passed to it.

    foo(val1, val2, val_n);

    A function defined with parameters can produce a result that changes dynamically depending on the passed values.

    Default Parameters in PHP

    Here is the way you can set default values for function parameters in PHP so that arguments become optional.

    <?php
       function greet($name = "Guest") {
    
      echo "Hello, $name!";
    } greet(); echo "\n"; greet("Rashmi"); ?>

    Output

    It will produce the below result −

    Hello, Guest!
    Hello, Rashmi!
    

    Variable Length Arguments in PHP

    In PHP, you can also define variable-length parameters if you do not know the number of parameters in advanced. Here is the way you can create functions that accept a dynamic number of arguments using ‘….’.

    <?php
       function sumAll(...$numbers) {
    
      return array_sum($numbers);
    } echo sumAll(1, 2, 3, 4); ?>

    Output

    It will generate the below result −

    10
    

    Function to Add Two Numbers

    The following code contains the definition of addition() function with two parameters, and displays the addition of the two. The run-time output depends on the two values passed to the function.

    <?php
       function addition($first, $second) {
    
      $result = $first+$second;
      echo "First number: $first \n";
      echo "Second number: $second \n"; 
      echo "Addition: $result";
    } addition(10, 20); $x=100; $y=200; addition($x, $y); ?>

    Output

    It will generate the following output −

    First number: 10 
    Second number: 20 
    Addition: 30 
    First number: 100 
    Second number: 200 
    Addition: 300
    

    Formal and Actual Arguments

    Sometimes the term argument is used for parameter. Actually, the two terms have a certain difference.

    • A parameter refers to the variable used in function’s definition, whereas an argument refers to the value passed to the function while calling.
    • An argument may be a literal, a variable or an expression
    • The parameters in a function definition are also often called as formal arguments, and what is passed is called actual arguments.
    • The names of formal arguments and actual arguments need not be same. The value of the actual argument is assigned to the corresponding formal argument, from left to right order.
    • The number of formal arguments defined in the function and the number of actual arguments passed should be same.

    Example

    PHP raises an ArgumentCountError when the number of actual arguments is less than formal arguments. However, the additional actual arguments are ignored if they are more than the formal arguments.

    <?php
       function addition($first, $second) {
    
      $result = $first+$second;
      echo "First number: $first \n";
      echo "Second number: $second \n";
      echo "Addition: $result \n";
    } # Actual arguments more than formal arguments addition(10, 20, 30); # Actual arguments fewer than formal arguments $x=10; $y=20; addition($x); ?>

    Output

    It will produce the below output −

    First number: 10 
    Second number: 20 
    Addition: 30 
    PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments
    to function addition(), 1 passed in /home/cg/root/20048/main.php
    on line 16 and exactly 2 expected in /home/cg/root/20048/main.php:2
    

    Arguments Type Mismatch

    PHP is a dynamically typed language, hence it doesn’t enforce type checking when copying the value of an actual argument with a formal argument. However, if any statement inside the function body tries to perform an operation specific to a particular data type which doesn’t support it, PHP raises an exception.

    In the addition() function above, it is assumed that numeric arguments are passed. PHP doesn’t have any objection if string arguments are passed, but the statement performing the addition encounters exception because the “+” operation is not defined for string type.

    Type Error with String Arguments

    Take a look at the following example −

    <?php
       function addition($first, $second) {
    
      $result = $first+$second;
      echo "First number: $first \n";
      echo "Second number: $second \n";
      echo "Addition: $result";
    } # Actual arguments are strings $x="Hello"; $y="World"; addition($x, $y); ?>

    Output

    It will create the following outcome −

    PHP Fatal error:  Uncaught TypeError: Unsupported operand types: string + string in hello.php:5
    

    However, PHP is a weakly typed language. It attempts to cast the variables into compatible type as far as possible. Hence, if one of the values passed is a string representation of a number and the second is a numeric variable, then PHP casts the string variable to numeric in order to perform the addition operation.

    Automatic Type Conversion

    Take a look at the following example −

    <?php
       function addition($first, $second) {
    
      $result = $first+$second;
      echo "First number: $first \n";
      echo "Second number: $second \n";
      echo "Addition: $result";
    } # Actual arguments are strings $x="10"; $y=20; addition($x, $y); ?>

    Output

    It will produce the following output −

    First number: 10 
    Second number: 20 
    Addition: 30
    
  • Functions

    Like most of the programming languages, a function in PHP is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reuse.

    PHP supports a structured programming approach by arranging the processing logic by defining blocks of independent reusable functions. The main advantage of this approach is that the code becomes easy to follow, develop and maintain.

    The following figure shows how the process of salary computation is successively broken down to independent and reusable functions.

    PHP Functions

    Types of Functions

    You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well. There are two types of functions in PHP −

    • Built-in functions − PHP’s standard library contains a large number of built-in functions for string processing, file IO, mathematical computations and more.
    • User-defined functions − You can create user-defined functions too, specific to the requirements of the programming logic.

    A function may be invoked from any other function by passing required data (called parameters or arguments). The called function returns its result back to the calling environment.

    There are two parts which should be clear to you −

    • Creating a PHP Function
    • Calling a PHP Function

    In fact you hardly need to create your own PHP function because there are already more than 1000 built-in library functions created for different area and you just need to call them according to your requirement.

    Please refer to PHP Function Reference for a complete set of useful functions.

    Why Use Functions?

    Here are some of the reasons provided to explain why you should use functions −

    • Reusable code is defined as code that can be written once and used repeatedly.
    • Breaking code into smaller parts makes it easier to maintain.
    • Functions clarify and arrange the code.

    Creating a Function in PHP

    Now let’s understand the process in detail. The first step is to write a function and then you can call it as many times as required.

    To create a new function, use the function keyword, followed by the name of the function you may want to use. In front of the name, put a parenthesis, which may or may not contain arguments.

    It is followed by a block of statements delimited by curly brackets. This function block contains the statements to be executed every time the function is called. The general syntax of defining a function is as follows −

    <?php   
       function foo($arg_1, $arg_2, $arg_n) {
    
      statements;
      return $retval;
    } ?>

    If the function is intended to return some result back to the calling environment, there should be a return statement as the last statement in the function block. It is not mandatory to have a return statement, as even without it, the program flow goes back to the caller, albeit without carrying any value with it.

    Any valid PHP code may appear inside a function, even other functions and class definitions. Name of the function must follow the same rules as used to form the name of a variable. It should start with a letter or underscore, followed by any number of letters, numbers, or underscores.

    Here is a simple function in PHP. Whenever called, it is expected to display the message “Hello World”.

    functionsayhello(){echo"Hello World";}

    User-defined Functions in PHP

    Its very easy to create your own PHP function. Let’s start with a simple example after which we will elaborate how it works. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it.

    Example

    In this example, we create a function called writeMessage() and then call it to print a simple message −

    <?php
       /* Defining a PHP Function */
       function writeMessage() {
    
      echo "You are really a nice person, Have a nice time!";
    } /* Calling a PHP Function */ writeMessage(); ?>

    Output

    It will produce the following output −

    You are really a nice person, Have a nice time!
    

    Calling a Function in PHP

    Once a function is defined, it can be called any number of times, from anywhere in the PHP code. Note that a function will not be called automatically.

    To call the function, use its name in a statement; the name of the function followed by a semicolon.

    <?php
       # define a function
       function sayhello(){
    
      echo "Hello World";
    } # calling the function sayhello(); ?>

    Output

    It will produce the following output −

    Hello World
    

    Assuming that the above script “hello.php” is present in the document root folder of the PHP server, open the browser and enter the URL as http://localhost/hello.php. You should see the “Hello World” message in the browser window.

    In this example, the function is defined without any arguments or any return value. In the subsequent chapters, we shall learn about how to define and pass arguments, and how to make a function return some value. Also, some advanced features of PHP functions such as recursive functions, calling a function by value vs by reference, etc. will also be explained in detail.

    Additional Key Concepts in PHP Functions

    Here are the key concepts used in php functions −

    • Function Parameters and Arguments: Pass data to functions and specify default values.
    • Return Values: Use return to send the results back to the caller.
    • Variable Scope: Understand local and global variables, as well as the global keyword.
    • Anonymous Functions: Create functions with no names (closures).
    • Built-in Functions: Use PHP’s pre-defined functions (such as strlen() and date()).
    • Recursive Functions: The functions are those that call themselves (for example, factorial calculation).
    • Function Overloading: func_get_args() accepts multiple parameters.
    • Passing by Reference: Use & to modify variables directly.
    • Type declarations: Enforce the argument and return types (int, string).
    • Error Handling: Manage errors with try, catch, and exceptions.