unknown os platform
Free Beginner PHP Tutorials - Functions with return value | Whats-online.info

Free Beginner PHP Tutorials - Functions with return value

2016:09:26 / Science and Tutorials

PHP functions that return a value

PHP Functions with return value

For this article, we will discuss how to create user-defined functions in PHP that returns a value. Besides, I will demonstrate this post using two functions. One with argument and the other with no argument.

Note: To let a function return a value, we use the return statement. Also, a function returns only one value either a variable or an array.


example 1 (with arguments )

<?php  //with arguments   function areaOfSquare1($width,$height){         $area=$width*$height;          return $area; } //calling the function echo "The area of a square is: ". areaOfSquare1(20,10); ?>

example 2 (with no arguments)

<?php  //with no arguments    function areaOfSquare2(){         $area=20 * 10;          return $area; } //calling the function echo"The area of a square is: ".areaOfSquare2(); ?>

The above example 1 and 2 will output the same results.
Results: The area of a square is: 200.

The advantage of example 1 over 2 is, you can pass multiple values and execute the function to print out different results.


<?php echo"Area of rectangle A is: ".areaOfSquare1(20,10)."<br>"; echo"Area of rectangle B is: ".areaOfSquare1(30,10)."<br>"; echo"Area of rectangle C is: ".areaOfSquare1(40,10)."<br>"; ?>

Area of rectangle A is: 200
Area of rectangle B is: 300
Area of rectangle C is: 400

You may also like:

Leave a comment

Subscribe to get replies direct to your mailbox

Submit comment