1. Computing

Learn PHP - All About PHP Functions

By , About.com Guide

4 of 5

Writing Functions
While having pre-made functions is useful, for most things you are going to want the flexibility to write your own custom functions. A function you create takes this shape: function functionname () { your code }

Below is an example of two simple functions:

 <?php 
 function examplefunction () 
 	{ 
 	print "Hi, I'm a Function <br>"; 
 	} 
 function sqr( $num ) 
 	{ 
 	$NumSqr = $num * $num; 
 	return $NumSqr; 
 	} 
 Print "Sample Line 1 <br>"; 
 examplefunction(); 
 Print "Sample Line 3 <br>"; 
 $a = 9; 
 $b = sqr( $a ); 
 Print $a . "^2 = " . $b; 
 ?> 

As you can see above, the code we defined between the { and } is all executed when we call the function below. In our first example (examplefunction) we used the function to simply print text. In our second function (sqr) we needed an operand to complete the math within the function. We put this inside the parenthesis () after the function name. We then add in the RETURN line, so that the value is outputted to the spot in the code where we originally called the function.

  1. About.com
  2. Computing
  3. PHP / MySQL
  4. PHP Functions
  5. Write Functions Tutorial - Learn to Write Functions - PHP Functions

©2013 About.com. All rights reserved.