article

Saturday, August 3, 2013

Defining and Using Functions in PHP

Defining and Using Functions in PHP 

A function is a self-contained piece of code which carries out a particular task or function. benefit of using functions is that they are reusable


<?php
//Defining a Function
//syntax for defining a function
function addNumbers($num1, $num2) {
    $result = $num1 + $num2;
    return $result;
}
$total = addNumbers(5, 10); 
//echo $total; //result 15

//Organizing Functions
function hello() {
    echo "<h1>HELLO!</h1>";
    echo "<p>Welcome to my web site</p>";
}

function printBreak($text) {
    echo "$text<br>";
}

function addNumbers($num1, $num2) {
     return $num1 + $num2;
}

echo hello();
echo printBreak("This is a line");
echo addNumbers(3.75, 5.645); //9.39536.75

//Accepting a Variable Number of Arguments
function calcAverage() {
    // initialize value to be used in calculation
    $total = 0;       

    // find out how many arguments were given
    $arguments = func_num_args();      

    // loop to process each argument separately
    for ($i = 0; $i < $arguments; $i++) {
        // add the value in the current argument to the total
        $total += func_get_arg($i);
    }

    // after adding all arguments, calculate the average
    $average = $total / $arguments;  

    // return the average
    return $average;
}

// invoke the function with 5 arguments
//echo calcAverage(44, 55, 66, 77, 88); //output 66   

// invoke the function with 8 arguments
echo calcAverage(12, 34, 56, 78, 90, 9, 8, 7); //ouput 36.75

Related Post