PHP Functions Part2

 PHP Functions Tutorial

 


 

 PART1

Types of User Defined Functions

In previous tutorial, you learn what is a function.

A function is nothing but a named block, that will perform a specific task. 

A function can be written in four ways based on the requirement.

1. Function with no arguments no return
2. function with arguments
3. function with return
4. function with arguments with return.


Arguments: are inputs to the function
return: function returns the result (output).

Note:  arguments and return are optional 

 

1. Function with no arguments no return.

TOC

Example:

<?php

function hello() {
 
    print("Hello world! <br>"); 

}

hello();

?>

A function, can be called any number of times.

<?php

function hello() {
 
    print("Hello world! <br>"); 

}

hello();

?>
 

A function can be called in a loop.

 
 
<?php
 
function hello() {
 
    print("Hello world! <br>"); 

} 
 
for($i=0 ; $i<5 ; $i++) 
{
    hello();
}
 
?> 
 

2. function with arguments

  
 

A function takes variables as an argument.


Example1: 

 
<?php
 
function writeName($fname,$lname)
{
    echo "<br>My firstname is " . $fname;
    echo "<br>My lastname is ". $lname;
}
    writeName("John","Deo");
 
?> 
 

 

function with array argument.In PHP a function can take an array as a arugment.

 

Example2: 

 

 

<?php
 
function total_items($colors
 
{
    foreach($colors as $color)
    {
        print $item. "<br> ";
    }
 
     print "<br>Total items =".count($items); 
 
}
 
print("<br>");
 
$colors = array("red", "green", "blue", "orange"); 
 
total_items ($colors);
 
 
?>  

 

Add one more color like “purple” at the end of the array and execute it. Now the count is 5

 

 

3. function with return.


TOC

 
<?php
 
function add()
{
    $x = 10; $y = 20;  // x,y are local variables
    return ($x+$y);
}
 
$sum= add();
 
echo "Result: ". $sum;  // return value printed here
 
?>

 

Output:

Result: 30 

 

4. function with arguments with return.

 

TOP

 

<?php

function multiply($x, $y)
{
    return ($x * $y);
}

$result = multiply(2,16);  // returned result storing in variable
 
echo "<br>Multiply: ". $result;
 
echo "<br>Result: ". multiply(5,6); // returned result directly printed here.

?>
 

Output:

Multiply: 32

Result: 30

 
 


PHP HOME


GOTO PART1

 

Comments

Popular posts from this blog

Using javascript pass form variables to iframe src

Creating a new PDF by Merging PDF documents using TCPDF

Import excel file into mysql in PHP