Functions


A function is just a section of code that can executed whenever and where you want it to be. The great thing about functions, is that you can use them over and over! It's great because once you create a function that you use more than once, it saves you time on more coding.
You can create your own function, or use one of the hundreds built in functions that PHP offers. You should also know that functions can confusing, and understanding them at first can be difficult for some people. If you're one of those people who ends up having a hard time understanding functions, just keep trying!
This class is long and has a lot of code in it - don't be intimidated by it, I try my best to keep it simple!

Creating your own function:
It's pretty simple to create a function. Here's the syntax:

<?

function functionName()
{
    // code you want to use
}

?>

There are a few basic rules we should go over first. Your PHP functions should be named after what it does. It's much easier to keep track of which function does what if you use this method. And like a variable, it must start with a letter or underscore.
Let's go over the function syntax real quick:
To define a function, you must start your block of code with the word "function" and this will tell PHP, "This is a function I'm creating". Then you name your function, followed by (). Everything from your function will go inside the curly brackets. You can even call other functions inside a function!
Note: PHP's recursion is not very good, so if you try to make a function loop through itself ten thousand times.. There's a chance it won't.

Output:
This is something more tutorials and people won't tell you about PHP functions. There are 2 kinds of output:
Output that is created inside the function, and
Output that has to be called from outside the function.

Let's create out first function that outputs a string from inside the function.

<?

function favCar()
{
    echo "Audi";
}

?>

Ok, simple enough. Now let's see how we call it:

<?

echo "I really like ";
favCar();

?>

Displays:

I really like Audi

But what if we added favCar() into what we echo, like so:
<?="I really like " . favCar(); // Remember the shorthand way to echo? ?>
Displays:
AudiI really Like

That's a little backwards.. The reason why our script put "Audi" in front, was because it is trying to be echo'd inside an echo. PHP saw that code like this:
<? echo "I really like " . echo "Audi"; ?>

To remedy this, we use the return command instead of echo inside of our function.

<?

function favCar()
{
    return "Audi";
}

?>

What the return command does is shoot out the answer, and then you can use it inline with a echo command. Think of return like the answer to a solution; 1 + 1 = return.
If this doesn't make any sense to you now, it probably will a little ways down the PHP Learning Road.

Parameters:
A parameter is an extra piece of information that you can feed to your function. The syntax is very similar, only now we add variables inside our regular brackets.

<?

function favCar($name)
{
    echo "My favorite car is " . $name;
}

?>

How to call it:

<?

favCar("Audi"); // Displays "My favorite car is Audi"

?>

$name in the function favCar is a variable, but when we call it, we used a string, which works as well. If we wanted to, we could use a variable rather than a string.

<?

$car = "Audi";
function favCar($name)
{
    echo "My favorite car is " . $name;
}
favCar($car); // Displays "My favorite car is Audi"; same result

?>

Functions can hold many parameters, but we're only going to use two in our next example.

<?

function add($a, $b)
{
    $answer = $a + $b;
    return $answer;

    /* Our we can use
    return $a + $b;
    as a shorter method, your choice! */

}
echo "10 + 5 = " . add(10, 5);

?>

All we did was add a comma after our first parameter, and added another parameter (that looks like a variable).
Our function called add will simply add the first number and the scond number together.
The return shoots out the $answer for $a + $b, and we display it on our page using the echo command.

Boolean:
Boolean logic is a form of algebra that returns TRUE or FALSE. (1 or 0). Don't worry, we don't do algebra in this course!
If something returns 1, it's TRUE. Or if it returns TRUE, it's 1. Same concept with FALSE.
If something returns 0, it's FALSE. Or if it returns FALSE, it's 0.

Let's look at how we fit this in with functions:

<?

function overTen($a, $b)
{
    $total = $a + $b;
    if($total>=10)
    {
        return true;
    }
    else
    {
        return false;
    }
}

if(overTen(5, 5)==true)
{
    echo "Our addition function said our result is equal to or greater than 10";
}
else
{
    echo "Our function's result was below 10";
}

?>

Don't panic! It's not as much code as you think it is. When we break down our code, it looks like this:
A function, and an if/else statement.
In our function, we created a variable that holds the answer to our two parameters.
It also has an if/else statement saying "If the answer is equal to or greater ten, return true. If it is else than 10, return false".
That's the entire function!

The if statement says this:
"If our function overTen() returns true, say '....'. But if it returns false, then say '....'"

So really, you already knew all the parts to that big chunk of code.

Once more, if any of this confuses you, please do not get frustrated (which all programmers do eventually) and quit. This is a major building block for your coding future, and a big help with other computer languages.

Your task:
Create a function that will echo "Hello world" from within itself.
Then create a function that will echo "Hello world", but needs to be echo'd outside of the function.
Then create a function that accepts 2 parameters and adds them together, returning your answer and displaying it.
Finally, create a boolean function that returns true of false, and use an if statement to echo different text on your page.

Once you finish all 4 tasks, you are officially able to write, understand, and use functions! Congratulations!

Task Discussion


  • Tynanh   March 26, 2013, 11:51 p.m.

    Check out my functions here

    functions.php

    I also made a game that uses functions to check user inputs against arrays to see if they answer a question correctly. There is a link in the page above or:

    function_game.php

  • katpal   July 4, 2012, 11:09 a.m.

    Hi, can you please help me?
    why does my code below does not work?
    it basically does not return the $age and $dif values back to the if statement:

    <?
    
    // boolean funtion
    
    function onTheFly($limit,$age)
    {    
    $dif=$limit - $age;
    
    if ($age >= $limit)
        {
                    return true;
            }
    else
    {    
            return false;
    }
    }
    //calling the function with values and displaying them in the sentence
    if (onTheFly(18,17)==true)
    {
        echo " <br>Hey you are " .$age. " years old you can drink!";
    }
    else
    {
        echo "<br> hey you are " .$age. " years old, you cannot drink! you need " .$dif. " more years to go";
    }
    
    ?>
  • Asier Iturralde Sarasola   July 4, 2012, 12:12 p.m.
    In Reply To:   katpal   July 4, 2012, 11:09 a.m.

    Hi katpal,

    I'm not an PHP expert but I will try to help.

    The scope of the variables $limit, $age, and $dif is the function onTheFly, that means that they only exist inside that function. The function returns true or false, nothing else. The variables that are inside the function cease to exist when the function ends.

    You are trying to use the variables out of their scope and that's why you get error messages that say "Notice: Undefined variable: age" and "Notice: Undefined variable: dif". These variables are not defined outside of the function onTheFly.

    Recommendations:

    • You should try to use meaningful variable and function names, for example, I think that something like canDrink is better than onTheFly.
    • Your function does two different things: checks if you can drink and calculates the difference between your age and the legal age. Each function should make one thing. I would create two functions: canDrink and calculateAgeDiff.

    Best regards,

    Asier Iturralde Sarasola

  • katpal   July 7, 2012, 2:37 a.m.
    In Reply To:   Asier Iturralde Sarasola   July 4, 2012, 12:12 p.m.

    Thanks Asier!
    well you are certainly fluent enough to see my mistake. Thanks for the advice!

    Here is my code below - and it works :)

    <?
    function canDrink($a,$b)
    {    
    if ($b >= $a)
        {
                    return true;
            }
    else
    {    
            return false;
    }
    }
    
    $dif;
    $myAge=17;
    $myLimit=18;
    
    function calcDifference($a,$b) {
        $dif=$a - $b;
        return $dif;
    }
    
    if (canDrink($myLimit,$myAge)==true)
    {
        echo " <br>Hey you are " .$myAge. " years old, you can drink!";
    }
    else
    {
        echo "<br> hey you are ".$myAge." years old, you cannot drink! you need ".calcDifference($myLimit,$myAge)." more years to go";
    }
    ?>
    
    

  • Asier Iturralde Sarasola   April 15, 2012, 9:57 a.m.

    Here is the code of my task.

    It displays this:

    Hello world

    Hello world

    1 + 2 = 3

    isEven(2) returns 1

    isEven(3) returns