PHP Functions || PHP

DATABASE PHP
PHP Functions is the block of code which takes some parameter , execute the code and return some value.

Construct PHP Function:

First of all we will write keyword “function” which is built-in, before the name of function.The name of function can’t start with the number,it can be any word like we declare variable in PHP but without dollar($) sign. The parameter of PHP function can be string ,number or variables.If the parameters are variables then it will be compulsory for us to pass value when we are calling it.

Example #1:

Simple Calling Php function.
 <?php

function  message(){
 echo "Hello World";
}
message();

?>

Output:

Hello world

Passing Arguments by Parameters:

The Parameters are pass inside the PHP function as string ,integer or variable.If the actual parameters are string or integer than they are pass to the variables present in the formal parameter. In case of variable as actual parameter, value inside the variable will be pass in formal parameter of function.

Example #2:

Sum of 5 numbers by function.
<?php

function  sum($num1, $num2,$num3,$num4,$num5){
        $sum=$num1+$num2+$num3+$num4+$num5;
        echo "The Sum =".$sum;
}
sum(5,5,5,5,5);

?>

Output:

The Sum =25

Example #3:

Passing variables to the functions.
<?php
$num=5;
function  sum($num1, $num2){
        $sum=$num1+$num2
        echo "The Sum =".$sum;
}
sum($num,$num);

?>

Output:

10

Passing Arguments by Reference:

The Passing by Reference means that we just pass reference of variable in the function, if its value manipulate than the actual value will be change.We use & with the formal parameters of function.

Example #4:

Assign values to Array using function.
<?php
$array=[];

function Ten_values(&$array){

    for($i=0;$i<10;$i++){
        array_push($array,$i);
    }

}
Ten_values($array);
print_r($array);
?>

Output:

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
    [6] => 6
    [7] => 7
    [8] => 8
    [9] => 9
)

Returning Value:

The return statement is use at the end of PHP functions to return some value,it can be string ,integer or array. It will return the value from where it was called.

Example #5:

<?php
$array=[10,20,34,32,43,5,34,3,232];

function average($array){  
    $sum=0;  
    for ($i=0;$i<sizeof($array);$i++){
            $sum=$array[$i]+$sum;    
    }
    $avg=$sum/sizeof($array);
    return $avg;
}

echo average($array);
?>

Output:

45.888888888889
 

Leave a Reply

Your email address will not be published. Required fields are marked *