Home Tutorial Php Phpbasics Tutorial PHP User Defined Function

 
 

PHP User Defined Function
Posted on: November 4, 2009 at 12:00 AM
Advertisement
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:

function add will return=123

Example 3:

<?php

function one()

{

    echo "We are inside the function.";

}

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

one();

?>

Output:

We are outside the function
We are inside the function.

Example 4:

<?php

function string_push($array,$str)

{

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

}

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

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

var_dump($array);

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

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

var_dump($array);

?>

Output:

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"
}

 

 

Advertisement

Related Tags for PHP User Defined Function:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 4, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com