PHP Functions

Spread the love

 

What is a Function:

PHP Functions are separate blocks of code which can be executed when gets called. A function can also accept optional parameters and after execution can return values to the caller. Let’s see PHP Functions in details.

Syntax:

<?php

function showName($first_name, $last_name)
{
echo "This is full name - " . $first_name . " ". $last_name;
return $first_name." " .$last_name;
}

?>

PHP Function with default values in optional parameters.

We can set optional parameters to default values in the function. If no parameters are passed to the function then the default values can be used.

Syntax:

<?php

function showAge($age = 22)
{
echo "The age is-";$age;
}

?>

Function parameter types:

  1. Pass by values
  2. Pass by reference

Pass by values:

In this type, we pass variable data to the functions directly. In this case, original variable data not get modified or changed, if we change passed value inside the function.

Example:

<?php
$age = 22;
showAge($age); //Calling function by sending $age value directly to the function.

function showAge($passeddata)
{
$passeddata = $passeddata + 10;
echo "<br>Age inside function = ".$passeddata;
}

echo "<br>Original age = ".$age;
?>

Output:
Age inside function = 32;
Original age = 22;

 

Pass by reference:

In pass by reference two variables point to the same data with different names. In this case, we pass the reference/address to another variable to which we want to assign. We have to use an ampersand(&) before the referenced variable name.

Example:

<?php
$a = 5;
$b = 15;

echo "<br>Original value of a = ".$a;
echo "<br>Original value of b = ".$b;
echo "<br>";

addParams($a);
addParams($b);

function addParams(&$test)
{
$test = $test + 5;
}

echo "<br>Updated value of a = ".$a;
echo "<br>Updated value of b = ".$b;
?>

Output:
Updated value of a = 10
Updated value of b = 20

Returning values from PHP functions:

We can return values or result of the operation performed inside the function to the caller of that function using “return” keyword.

Example:

<?php
$result = add(10, 20);
echo "Result of addition is = ".$result;

function add($a, $b)
{
$c = $a + $b;
return $c;
}

?>

Output:
Result of addition is = 30.

 


Spread the love

Leave a Comment