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"
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.