Home > PHP > Using Optional Argument with User Defined Functions in PHP

Using Optional Argument with User Defined Functions in PHP

Hi everybody. After a long time, I am here again with my new articles. I thought it can be good to start with a little clue for PHP coders.

Usage of PHP functions is so easy and practical. However, usually we need to write our own functions while we are making our applications.

1.1) User Defined Functions in PHP

Structure 1.0:

1
2
3
4
5
6
7
<?php
function FunctionName( arguments ){

//php codes

}
?>

The function ends when return() statement is executed.

Example 1.1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php  function TakeFactorial($number){
if($number==0)$number=1;
if($number>0)for($i=$number-1;$i>0;$i--)$number*=$i;
return $number;
}
echo takefactorial(5). "<br>";

//We can also equalize the $factorial variable
//to result of takefactorial() function.
//Because we used return statement in function.
//The returned value will be appointed to our variable.
$factorial=takefactorial(4);
echo $factorial;
?>


Output of Example 1.1:

1
24

There is a simple function that takes factorial of a number.

Example 1.2:

1
2
3
4
5
6
7
8
9
<?php  function TakeFactorial($number){
if($number==0)$number=1;
if($number>0)for($i=$number-1;$i>0;$i--)$number*=$i;
echo $number; }
takefactorial(5);

//This time we cannot use the result of takefactorial()
//function because there is no return() statemenet.
?>

Output of Example 1.2:

1
120

1.2) Using Optional Arguments with User Defined Functions in PHP

In some cases we don’t need to write all arguments in functions but if arguments of function are more than one, it is not possible to leave arguments empty. So we will define arguments values while we are defining the function. Let’s make it clear with an example.

Example 1.3: This example will not work!

1
2
3
4
5
6
7
<?php
function MyFunction($x,$y){
echo $x." - ".$y;
}

MyFunction(5);
?>

Output of Example 1.3:

1
Warning: Missing argument …

As you see this usage is not valid. Now, we are going to define the second argument in the function.

Example 1.3: This example will work!

1
2
3
4
5
6
7
8
9
10
11
12
<?php
function MyFunction($x,$y=NULL){
echo $x;
if($y!=NULL)echo " - ".$y;
echo " - end"
}

MyFunction(5);
echo "<br>";
MyFunction(5,8);

?>

Output of Example 1.3:

1
2
5 - end
5 – 8 - end

That’s all. Now you don’t have to write the second argument if you don’t need to… You can also equalize the $y argument to a string or to an integer. It’s up to you!

Bookmark and Share
  1. No comments yet.
  1. No trackbacks yet.
eXTReMe Tracker