PHP Function


Share

PHP comes with hundreds of ready-made, built-in functions, making it a very rich language.
PHP function works similar to other programing language.
for example, printf function used to print values.


Defining a Function

The general syntax of function is

function function_name([parameter [, ...]]) 
{
//statements
}

1. A definition starts with the word function.
2. Following that is a name, which must start with a letter or underscore, followed by any number of letters, numbers, or underscores.
3. The parentheses are required.
One or more parameters, separated by commas, are optional (indicated by the square brackets, which are not part of the function syntax)

Returning an Array

This function return the value using return keyword similar to other programming language.

<?php
   echo fix_names("WILLIAM", "Japi");
   function fix_names($n1, $n2, $n3)
   {
       $n1 = ucfirst(strtolower($n1));
       $n2 = ucfirst(strtolower($n2));
       return $n1 . " " . $n2;
    }
?>
    OUTPUT:
     William jepi 

Passing by Reference

Pass the value using by reference.

<?php
$a1 = "Apple"; 
$a2 = "Orange"; 
echo $a1 . " " . $a2 . " " . "
"; fix_names($a1, $a2); echo $a1 . " " . $a2; function fix_names(&$n1, &$n2) { $n1 = ucfirst(strtolower($n1)); $n2 = ucfirst(strtolower($n2)); } ?>
    OUTPUT:
    Apple Orange Apple Orange

Returning Global Variables

We can use global keyword in function for access variable value.

<?php
   $a1 = "Apple"; 
   $a2 = "Orange";
   echo $a1 . " " . $a2;
   fix_names();
   echo $a1 . " " . $a2;
   function fix_names()
   {
       global $a1; $a1 = ucfirst(strtolower($a1))
       global $a2; $a2 = ucfirst(strtolower($a2));
   }
?>