PHP Lesson 3 – Creating Functions

How to create Functions in PHP and also how to Pass Variables to Functions.

Introduction:

You will need to have a PHP web server for this tutorial. We recommend SimpleHost.com for only $7.50 with Unlimited Disk Space, Subdomains, and Emails Accounts.

PHP has hundreds of predefined functions (maybe thousands). This tutorial gives examples on how to create your own php functions. There are two rules I would like to share with you before we start.

Rule 1:
Make sure your new function name does not exhist. You can check PHP.net for a complete list of PHP predefined functions.

Rule 2:
Do not declare/define the same function more than once inside the same file. You will get an error.

OK, let’s create our first function. This function will display a text advertisement. We will call this function ads().

Source Code

<?php
// first define the function
function ads()
{
echo “Visit NewSourceMedia.com for free tutorials”;
}
// now call the function ads() like so
ads();
?>

Now you can display the same ad however many times you want just by calling the function ads().

Passing Values to Functions:

Let’s say we want to randomly display three ads. We could do this by placing three text ads inside our ads() function and then passing a random value to it, to indicate which ad to display. We can do this by using a parameter variable inside the function. For example $n will be the variable and this is how it is placed inside our ads function like so “ads($n)”. This variable holds a copy of the value passed to it.

Now we need to set $n to a random number between 1 and 3. We can do this by using one of PHP pre-defined functions called rand(). If you want a random number between 1 and 3 (inclusive), for example, use “rand (1, 3)”. To make this a little more clear, view the code below:

Source Code

<?php

// first define the function

function ads($n)
{

$a = “http://newsourcemedia.com”;

if($n == 1)
echo “<a href=’$a’>Visit NewSourceMedia.com for free tutorials</a>”;

if($n == 2)
echo “<a href=’$a’>NewSourceMedia.com for PHP and much more!</a>”;

if($n == 3)
echo “<a href=’$a’>PHP is Number One!</a>”

} // end of function

// define the random value for $n
$n = rand (1, 3);

// now call the function ads() with the value $n
ads($n);

?>

You may also like...

Leave a Reply