"Welcome to our PHP 101 blog, where we demystify the world of web development. "

Friday, June 15, 2018

Functions in PHP

PHP FUNCTIONS


What is PHP FUNCTIONS
A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.
Advantage of PHP Functions
  • Reducing duplication of code
  • Decomposing complex problems into simpler pieces
  • Improving clarity of the code
  • Code reusability
  • Information hiding
Types of PHP FUNCTIONS:
There are two basic types of functions:
  1.  Built-in functions and
  2.  user defined functions.
i) Built-in functions :
The built-in functions are part of the PHP language.
There are thousands of built-in functions in PHP that can be called directly from within a script to perform a specific task in PHP Functions.
Examples are: phpinfo(), round() or abs().

ii) user defined functions.
The user defined functions are created by application programmers .
How to Create a Function:
You can create a function using the function keyword.
Syntax:
function functionName() {
    code to be executed;
}
Rule to name a function name:
  1. A function name can start with a letter or underscore  and optionally followed by the more letters , numbers or underscore characters with round brackets,i.e; writeFunction().
  2. It cant be start with numbers or special symbols.
  3. The function names are case-sensetive.
  4. The body of the function lies between the curly brackets. 
We say that we call a function. If we call a function, the statements inside the function body are executed.
Example:
<?php
function writeFunction() {
    echo "Hello world!";
}
writeFunction(); // call the function
?>

Output:
Hello world!

Explanation:

  1. function writeFunction() { ... }: This line defines a PHP function named writeFunction. The function does not take any parameters and contains a single statement, which is to echo the string "Hello world!".
  2. writeFunction(); To call the function, just write the function name. This line calls (invokes) the writeFunction function. When this line is executed, the code inside the function is executed, and "Hello world!" is printed to the output.

PHP supports :

  1. Call by Value (default), 
  2. Call by Reference
  3. Default argument values and 
  4. Variable-length argument list.

1. PHP Functions with Parameters or Call by value:

PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like. These parameters work like variables inside your function. Following example takes two integer parameters and add them together and then print them.
Case 1: Passing single argument in PHP function.

File: functionarg.php
<?php  
function sayHello($name){  
echo "Hello $name<br/>";  
}  
sayHello("Sonoo");  
sayHello("Vimal");  
sayHello("John");  
?>  
Output:
Hello Sonoo
Hello Vimal
Hello John

Explanation:
  1. function sayHello($name) { ... }: This line defines a PHP function named sayHello that takes one parameter $name. Inside the function, it echoes a greeting with the provided name.
  2. sayHello("Sonoo");   This line calls the sayHello function with the argument "Sonoo". The function is executed, and it echoes "Hello Sonoo".
  3. sayHello("Vimal");  Similarly, this line calls the sayHello function with the argument "Vimal", resulting in the output "Hello Vimal".
  4. sayHello("John");: Again, this line calls the sayHello function with the argument "John", and the output is "Hello John".
case 2 : Passing  two argument in PHP function.:

In PHP, you can define a function that accepts multiple parameters by listing them within the parentheses of the function definition. 
Example:
functionarg2.php
<?php  
function sayHello($name,$age){  
echo "Hello $name, you are $age years old<br/>";  
}  
sayHello("Sonoo",27);  
sayHello("Vimal",29);  
sayHello("John",23);  
?>  
Output:

Hello Sonoo, you are 27 years old
Hello Vimal, you are 29 years old
Hello John, you are 23 years old

Explanation:
  1. function sayHello($name, $age) { ... }: This line defines a PHP function named sayHello that takes two parameters, $name and $age. Inside the function, it echoes a greeting with the provided name and age.
  2. sayHello("Sonoo", 27);: This line calls the sayHello function with the arguments "Sonoo" and 27. The function is executed, and it echoes "Hello Sonoo, you are 27 years old".
  3. sayHello("Vimal", 29);: Similarly, this line calls the sayHello function with the arguments "Vimal" and 29, resulting in the output "Hello Vimal, you are 29 years old".
  4. sayHello("John", 23);: Again, this line calls the sayHello function with the arguments "John" and 23, and the output is "Hello John, you are 23 years old".

Example 2:

<?php
function addFunction($n1,$n2)
{
$sum=$n1+ $n2;
echo “The sum of two numbers is : $sum”;
}
addFunction(10,20);
?>
Output:
The sum of two numbers is :30

Explanation :
  1. function addFunction($n1, $n2) { ... }: This line defines a PHP function named addFunction. The function takes two parameters, $n1 and $n2. Inside the function, the sum of these two parameters is calculated and stored in the variable $sum.
  2. $sum = $n1 + $n2;: This line calculates the sum of the two parameters passed to the function and assigns the result to the variable $sum.
  3. echo "The sum of two numbers is: $sum";: This line uses the echo statement to output a string that includes the calculated sum. The variable $sum is interpolated into the string.
  4. addFunction(10, 20);: This line calls (invokes) the addFunction function with the arguments 10 and 20. When the function is called, it calculates the sum of 10 and 20, and then echoes the result, resulting in the output "The sum of two numbers is: 30".

Functions with Optional Parameters and Default Values

You can also create functions with optional parameters — just insert the parameter name, followed by an equals (=) sign, followed by a default value, like this.
Example:
<?php
function customFont($font,$size=1.5){
echo “<p style=\”font-family:$font;font-size: {$size } em; \>”>Hello,world! </p>”;
}
customFont(“Arial”,2);// calling function
customFont(“Times”,3);// calling function
customFont(“Courier”,2);// calling function
customFont(“Arial”);// calling function
?>
Output:
<p style="font-family: Arial; font-size: 2em;">Hello, world!</p>
<p style="font-family: Times; font-size: 3em;">Hello, world!</p>
<p style="font-family: Courier; font-size: 2em;">Hello, world!</p>
<p style="font-family: Arial; font-size: 1.5em;">Hello, world!</p>
Explanation:
  1. function customFont($font, $size = 1.5) { ... }: This line defines a PHP function named customFont. The function takes two parameters, $font (for the font family) and $size (for the font size). The $size parameter has a default value of 1.5.
  2. echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello, world!</p>";    This line uses the echo statement to output an HTML paragraph (<p>) with a specified font family and font size. The font family is determined by the $font parameter, and the font size is determined by the $size parameter. The {$size} syntax is used to interpolate the variable within the string.
  3. customFont("Arial", 2);               This line calls (invokes) the customFont function with the arguments "Arial" and 2. The function is executed, and it echoes a paragraph with the specified font family and size.
  4. customFont("Times", 3);                    Similarly, this line calls the customFont function with the arguments "Times" and 3.
  5. customFont("Courier", 2);             This line calls the customFont function with the arguments "Courier" and 2.
  6. customFont("Arial");   This line calls the customFont function with the argument "Arial" and uses the default font size (1.5).
As you can see the 4th call to customFont() doesn't include the second argument. This causes PHP engine to use the default value for the $size parameter which is 1.5.

Returning Values from a Function

A function can return a value back to the script that called the function using the return statement. The value may be of any type, including arrays and objects.
<?php
function getSum($num1,$num2){ 
$total=$num1+ $num2;
return $total;
}
echo getSum(5,10)
?>
Output:
15
Explanation:
  1. function getSum($num1, $num2) { ... }: This line defines a PHP function named getSum. The function takes two parameters, $num1 and $num2. Inside the function, the sum of these two parameters is calculated and stored in the variable $total.
  2. $total = $num1 + $num2;: This line calculates the sum of the two parameters passed to the function and assigns the result to the variable $total.
  3. return $total;: This line returns the calculated total from the function.
  4. echo getSum(5, 10);: This line calls (invokes) the getSum function with the arguments 5 and 10. The function is executed, and it returns the sum (15). The echo statement then outputs the result.

Returning Multiple Values from a Function (Using array)

A function can not return multiple values. However, you can obtain similar results by returning an array, as demonstrated in the following example.
<?php
function divideNumbers($dividend,$divisor){ 
$ quotient =$dividend / $divisor;
$array=array($dividend,$divisor,$quotient);
return $array;
}
List($dividend,$divisor,$quotient)=devideNumbers(10,2);
echo $ dividend ;
echo $ divisor;
echo $ quotient;
?>
Output:
10
2
5
Explanations:
  1. function divideNumbers($dividend, $divisor) { ... }: This line defines a PHP function named divideNumbers. The function takes two parameters, $dividend and $divisor. Inside the function, the quotient is calculated, and an array containing $dividend, $divisor, and $quotient is returned.
  2. list($dividend, $divisor, $quotient) = divideNumbers(10, 2);: This line calls (invokes) the divideNumbers function with the arguments 10 and 2. The function returns an array, and list is used to assign the values of the array to the variables $dividend, $divisor, and $quotient.
  3. echo $dividend . '<br>';, echo $divisor . '<br>';, echo $quotient . '<br>';: These lines echo the values of $dividend, $divisor, and $quotient, each followed by a line break (<br>).

Passing Arguments to a Function by Reference

In PHP there are two ways you can pass arguments to a function: by value and by reference. By default, function arguments are passed by value so that if the value of the argument within the function is changed, it does not get affected outside of the function. However, to allow a function to modify its arguments, they must be passed by reference.
Passing an argument by reference is done by prepending an ampersand (&) to the argument name in the function definition, as shown in the example below:
<?php
function selfMultiply(&$number)
{
$number *=$number;
return $number;
}
$mynum=5;
echo $mynum;
selfMultiply($mynum);
echo $mynum;
?>
Output: 
25
Explanation:
In your PHP code, you are defining a function selfMultiply that takes a parameter by reference (&$number), multiplies the number by itself, and then returns the result. 
  1. $mynum = 5;: This line initializes a variable $mynum with the value 5.
  2. echo $mynum;: This line echoes the value of $mynum, which is 5. So, the first output is 5.
  3. selfMultiply($mynum);: This line calls the selfMultiply function, passing $mynum by reference. Inside the function, $number is multiplied by itself, and the updated value is stored back in $number.
  4. echo $mynum;: After the function call, this line echoes the updated value of $mynum, which is now 25 due to the reference modification inside the selfMultiply function. So, the second output is 25.

Creating Recursive Functions

A recursive function is a function that calls itself again and again until a condition is satisfied. Recursive functions are often used to solve complex mathematical calculations, or to process deeply nested structures e.g., printing all the elements of a deeply nested array.
Example:
<?php
function printValues($arr) {
    global $count;
    global $items;
    if (!is_array($arr)) {
        die("ERROR: Input is not an array");
    }
    foreach ($arr as $a) {
        if (is_array($a)) {
            printValues($a);
        } else {
            $items[] = $a;
            $count++;
        }
    }
    return array('total' => $count, 'values' => $items);
}
$species = array(
    "birds" => array("Eagle", "Parrot", "Swan"),
    "mammals" => array("Human", "cat" => array("Lion", "Tiger", "Jaguar"), "Elephant", "Monkey"),
    "reptiles" => array(
        "snake" => array(
            "Cobra" => array("King Cobra", "Egyptian Cobra"),
            "Viper",
            "Anaconda"
        ),
        "Crocodile",
        "Dinosaur" => array("T-rex", "Alamosaurus")
    )
);
$result = printValues($species);
echo $result['total'] . ' value(s) found: ';
echo implode(', ', $result['values']);
?>
Output:

17 value(s) found: Eagle, Parrot, Swan, Human, Lion, Tiger, Jaguar, Elephant, Monkey, King Cobra, Egyptian Cobra, Viper, Anaconda, Crocodile, T-rex, Alamosaurus

Explanation:
  1. This function, printValues, takes an array $arr as a parameter.
  2. Two global variables, $count and $items, are declared to keep track of the total count of values and an array of values, respectively.
  3. The function checks if the input is an array. If not, it terminates the script with an error message.
  4. The function then iterates over each element of the array. If an element is an array itself, the function is recursively called. If it's not an array, the value is added to the $items array, and the $count is incremented.
  5. The function returns an associative array with the total count and the array of values.
  6. An array named $species is initialized with a nested structure containing different types of animals.
  7. The printValues function is called with $species as an argument, and the result is stored in the $result variable.
  8. echo $result['total'] . ' value(s) found: ';
  9. echo implode(', ', $result['values']);
  10. The total count of values and the values themselves are echoed.
  11. The implode function is used to concatenate the values array into a string with commas between each value.

No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template