PHP Functions - How to make your own function

June 4, 2009    Create a function php Php development PHP functions

To keep the browser from executing a script when the page loads, you can put your script into a function.
A function will be executed by a call to the function.
You may call a function from anywhere within a page.

Create a PHP Function

A function will only be executed when a subsidiary piece of code calls it.

function functionName()
{
    // code to be executed;
}

Start by giving your function a name so in this case i will call my new function...findme();

function findme(){
    echo 'i found you';
}
findme();

As you will see from testing this my call to the function underneath it will make the browser execute the code inside the function echoing i found you onto the page.

Passing parameters to the function

Okay so we now have our findme() function which as it stands just echos something onto the page. This brings us to the two fundamental reasons for using functions. Firstly because they stop the use of repetitive code, if you needed to do the same 10 line or piece of code very often then you would save yourself alot of time by using a function to do so.

Functions are standalone so if you want the function to receive some kind of input so lets say for instance you have a form and you want to test what name was entered by the user.

function findme($name){

    if($name=='fred')
    { 
        echo 'dave';
    }
    elseif($name=='Bungle')
    {
        echo 'Sesame';
    }

}

if(isset($_POST['submit']))
{
    $name = $_POST['name'];
    findme($name);
}

The function will now check the inputted name from the form in the function.

Returning Values From A Function

So at the moment our function will echo what it finds, but what if we want it to just pass a variable out of the function back to us? Well you simply use the return php function.

function findme($name){

    if($name=='fred')
    {
        $nam = 'dave';
    }
    elseif($name=='Bungle')
    {
        $nam = 'Sesame';
    }

//$nam now contains the variable that we want our function to return so simply just do

return $nam;
}

if(isset($_POST['name']))
{
    $nam = findme($_POST['name']);
}

/* and thats it, now your $nam variable in your main php script will contain one of the names from above, providing someone enters one of the names i used in this example. */

This is the very basics of using and creating a php function! Check my other articles coming soon for more in depth articles!


blog comments powered by Disqus