1. Home
  2. Computing & Technology
  3. PHP / MySQL

Learn PHP - All About PHP Functions

By Angela Bradley, About.com

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.

Explore PHP / MySQL
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. Learn PHP
  5. Write Functions Tutorial - Learn to Write Functions - PHP Functions

©2009 About.com, a part of The New York Times Company.

All rights reserved.