Articles

Learn how to use PHP functions

How to Use Functions PHP lesson 10 Tutorials PHP

10. Functions and how to use them in PHP programming. Online Lesson about learning PHP coding.

10. Functions

Creating functions can save you lots of time. They are used to execute a self contained set of code, which can be called from within your script. If you need to execute a pattern of code instead of writing it multiple times you can use functions. In addition you can change the functions to suit your dynamic variables.

A function will contain a code grouping can can get called from within your script. To setup a function you identify it as a function with the syntax function and then the function name and in the brackets any variable you want to pass. The value will be assigned to the variable name that is within the function. Every function then contains its own set of variables that it uses so $a outside the function will not be the same as $a within the function.

$a = 1;
$b = 2;
$c = 3;

PHP Code example

function myAdd($a){
      echo "This value is now ". ($a + 5) . "
"; }

myAdd($a);
myAdd($b);
myAdd($c);

PHP output display

This value is now 6
This value is now 7
This value is now 8

notice how the $a in the function is not related to the root main $a. $a within the function is assigned whatever value the calling function has in its parameter.

With functions you are also able to return values on the fly.

$a = 1;
$b = 2;
$c = 3;

PHP Code example

function myAdd($a){
      $newValue = $a + 5;  
		return $newValue
}

myAdd($a) . "
";
myAdd($b). "
";
myAdd($c). "
";

PHP output display

6
7
8

***
Do Not Sell My Personal Information