PHP Tutorial Tutorials - PHP Functions

PHP Functions

A function is a piece of code that performs a specific task.
It can be executed whenever we need it.
PHP provides a large number of built-in core functions to that you can call directly.

The Advantage of Using Functions

  • Less Code: By generalizing the code in to a single common function, you don't need to write blocks of same code in multiple places.
  • Code Reusability: The function is defined only once and can be invoked whenever we need it.
  • Code is more Readable: Simpler functions are easier to understand.

PHP User-defined functions

Creating your first php function.
A function may be defined using syntax such as the following:

function FunctionName($param_1, $param_2, /* ..., */ $param_n)
{
    // Code to be executed
    return $retval;
}

When you create a function,You also need to give it a name FunctionName, then tell PHP that you want to create a function. You do this by typing the keyword function followed by your function name.
Function names follow the same rules as variables. A valid function name starts with a letter or underscore.

$param_1, $param_2, /* ..., */ $param_n is a list of expressions delimited by comma, also known as Parameter list.

Using your function

The function can be invoked by following statement syntax:

FunctionName();
FunctionName(`argument list`);

parameter is the variable when you define a function.
argument is the actual value that you pass to a function when it is called.

PHP Functions within functions

A function definition must be processed prior to being called.

In the following example,we can call bar() when function foo() is called.

<?php
function foo() 
{
  function bar() 
  {
    echo "I don't exist until foo() is called.\n";
  }
}
foo();
bar();
?> 

PHP Function arguments

You can specify parameters when you define your function to pass information to function.
It's a comma-delimited list of expressions called parameter list.

function FunctionName($param_1, $param_2, /* ..., */ $param_n)
{
    // Code to be executed
}

when the function is called ,the variables are called Arguments

<?php
// Defining function
// int1, int2 is known as parameter list
function getSum($int1, $int2){
  $sum = $int1 + $int2;
  echo "$int1 + $int2 =  $sum <br>";
}

$a = 3;
$b = 5;
// Calling function
getSum($a, $b); // $a, $b is called argument list
getSum(10, 20);
?>

Passing arguments to functions by reference

By default, function arguments are passed by value.
You can pass them by reference to allow a function to modify these arguments.
It is done by prepending an ampersand (&) to the argument name when define the function.

<?php
// there is a & prepend to argument.
function square(&$number)
{
    $number = $number*$number;
}
$num = 3;
square($num);
echo $num;    // outputs: 9
?> 

Set default argument values for functions

The function may define default values for scalar arguments.

  • The default value must be a constant expression (Integer,String,Array,NULL)
  • any default arguments should be on the right side of any non-default arguments
<?php
function printUrl($page,$website = "lautturi.com")
{
    echo $website."/".$page;
    echo "<br>";
}
printUrl("index.php");
printUrl("home.html","test.lautturi.org");
?>

Outputs:

lautturi.com/index.php
test.lautturi.org/home.html

Specify the parameter data type in PHP Functions

Type declarations allow functions to require that parameters are of a certain type at call time.

<?php
function testTypeDeclarations(array $param) {
 foreach ($param as $value){
    echo "$value ";
 }
}

testTypeDeclarations(array(1,2,3,4)); // 1 2 3 4
testTypeDeclarations(1234); // Fatal error: Uncaught TypeError: Argument 1 passed to testTypeDeclarations() must be of the type array, integer given
?>

Access ariable-length Arguments in PHP Functions

PHP also supports Variable-length argument lists.
Function can use the ... token to accepts a variable number of arguments as an array.

<?php
function testArg(...$args) {
    $argNum = count($args);
    echo "There are $argNum arguments passed to the Function<br>";
    echo "Argument list :";
    foreach ($args as $arg) {
        echo "$arg ";
    }
    echo "<br>"; 
}
testArg(1, 2);
testArg(1, 2, 3);
?>

Outputs:

There are 2 arguments passed to the Function
Argument list :1 2 
There are 3 arguments passed to the Function
Argument list :1 2 3 

Returning values From a PHP Function

A function can return a value back to the function caller using the optional return statement.
The return statement would cause the function to end its execution immediately and return program control to the calling module.

<?php
function sum($num1, $num2) {
    $sum = $num1 + $num2;
    return $sum;
}

echo sum(2, 5); // 7
?>

Returning An array From a PHP Function

A function can not return multiple values, You could,alternatively, obtaine similar results by returning an array.

Returning an array to get multiple values

<?php
function circle($r) {
    $pi = 3.14;
    $_perimeter = 2*$pi*$r;
    $_area = $pi*$r*$r;
    return [$_perimeter,$_area];
}

list ($perimeter, $area) = circle(5);
echo "perimeter:$perimeter<br>"; // perimeter:31.4
echo "area:$area<br>"; // area:78.5
?>

Returning a reference from a function

PHP Variable functions

If a variable name has parentheses() appended to it, PHP will look for a function with the same name as the variable value, and will attempt to execute it.

<?php
function foo(){
    echo "foo function<br>";
}
$name = 'foo';
$name(); // foo function
?>

PHP built-in functions

PHP provides lots of internal (built-in) functions. For some of them, you can call directly.
Some of them require specific PHP extensions compiled in.
Please check out the PHP reference section for a complete list of useful PHP built-in functions.

PHP Anonymous functions

PHP also support anonymous functions which have no specified name. they are also known as closures.
the most popular occasions to use them as the value of callback parameters.

<?php
$string = 'August 7, 2017';
$pattern = '/(\w+) (\d+), (\d+)/i';
$newStr = preg_replace_callback($pattern, function ($match) {
    return $match[1]." ".$match[2].", 2020";
}, $string);

echo $newStr; // August 7, 2020
?>

The anonymous function also can be assigned to a variable as the value.

<?php
$greet = function($name)
{
    echo "Hello $name<br>";
};

$greet('Lautturi.com'); // refer to Variable function section
?>

Outputs:

Hello Lautturi.com
Date:2019-10-01 02:47:37 From:www.Lautturi.com author:Lautturi