PHP User Defined Function


 

PHP User Defined Function

PHP User Defined Function: In this tutorial you will get to know about the user defined functions, how to declare, call, pass parameters etc. Examples will help you to go through user-defined functions.

PHP User Defined Function: In this tutorial you will get to know about the user defined functions, how to declare, call, pass parameters etc. Examples will help you to go through user-defined functions.

PHP User Defined Function

An user-defined function saves  us from  rewriting the same code again and again and helps us to make our application smaller. The given examples will help to understand how you can put them to work.

PHP has so many built-in functions, besides  that you can make your own functions as per the need. General structure of the user defined function is:

function function_name([mixed $var,.....]){ PHP code}

mixed is the datatype that means it could be of any datatype.

$var: is the name of the parameter, one function could have one,  more than one or no parameter.

Example 1:

<?php

function add($first,$second)

{

return ($first+$second);

}

$first=12;

$second=13;

echo "function add will return=".add($first,$second);

/*You might know these variables are

* different from the parameters of add function.

*/

?>

Output:

function add will return=25

Example 2:

<?php

function add($first,$second=23)

{

    return ($first+$second);

}

$first=100;

echo "function add will return=".add($first);

?>

Output:

0
function add will return=123

Example 3:

<?php

function one()

1

{

    echo "We are inside the function.";

}

2

echo "We are outside the function<br/> ";

one();

?>

3

Output:

We are outside the function
We are inside the function.

Example 4:

<?php

4

function string_push($array,$str)

{

    return(array_push($array,$str));

5

}

$array=array("This","is","new");

echo"<br/><b>Before calling string_push function</b><br/>";

6

var_dump($array);

echo"<br/><b>After calling string_push function</b><br/>";

$array=array($array,"array");

7

var_dump($array);

?>

Output:

8
Before calling string_push function
array(3) {
  [0]=>
  string(4) "This"
  [1]=>
  string(2) "is"
  [2]=>
  string(3) "new"
}

After calling string_push function
array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(4) "This"
    [1]=>
    string(2) "is"
    [2]=>
    string(3) "new"
  }
  [1]=>
  string(5) "array"
}

 

 

Ads