PHP 5 Functions

Today i'm here to share my new research about PHP Functions
i hope you will learn what you want and i hope this article is helpful to you


PHP FUNCTIONS

  • PHP is more powerful with its built in functions.
  • PHP has more than 1000 built in functions.
  • PHP also provides an ability to create user defined functions.
  • User can define their own functions in PHP it is called user defined functions.

Tthere are following types of functions :

  • User defined function
  • Returning value function
  • Variable function
  • Internal (in-built) function
  • Anonymous function
 User Defined Functions :

- User defined functions is used when you want something different.

Syntax :

function functionName()
{
    code to be executed;
}

This type of functions can be defined as follows :

 <?php
  function bar($arg1, $arg2,…,)
  {
    echo “test function”;
  }
?>

Rules to define function name :

  • Function name must be start with underscore ( _ ) OR a letter
  • First character can not be a digit
  • See more at php.net
Example :<?php
function writeMsg() {
     echo "Hello world!";
}

writeMsg();
?>

Output :

Hello world!


Functions Argument in PHP :

  • Functions Arguments are like a variables.
  • Function Arguments are used to passed information to the function.
  • user can specified the arguments to the functions.
  • to specified function arguments you have to write just after function name inside the parentheses.

    e.g

    function name(arg1, arg2)
    {
    code to be executed;
    }
  • You can specified more than one argument as you want, just separate them with comma ( , )
Example :

<?php
function familyName($fname) {
     echo "$fname Refsnes.<br>";
}

familyName("Sarjil Shaikh");
familyName("Shahnawaz Saiyed");
familyName("Salman Ansari");
familyName("Mitali Patel");
familyName("Roshni Panchal");
?>



Output: 

Sarjil Shaikh
Shahnawaz Saiyed
Salman Ansari
Mitali Patel
Roshni Panchal



Default Argument In php Finctions:


When user called functions without entering parameters the the functions takes Default argument.

Example :

<!DOCTYPE html>
<html>
<body>

<?php
function setHeight($minheight = 60)
{
   echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight(); // will use the default value of 60
setHeight(135);
setHeight(80);
?>

</body>
</html> 


Output :

The height is : 350
The height is : 50
The height is : 135
The height is : 80



PHP Functions - Returning values :

  • To let a function return a value, use the return statement: 
Example :

<?php
function sum($x, $y)
{
$z = $x + $y;
return $z;
}

echo "5 + 10 = " . sum(5,10) . "<br>";
echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>
 

Output :

5 + 10 = 15
7 + 13 = 20
2 + 4 = 6

Comments