Functions

PHP Functions are extremely useful, and they can save you from writing bunch of redundant code. These are arguably the most power component to any language. It can separate your code to create a sense of logical flow. You can also add parameters, or arguments to functions, where you can see that power at the bottom of this page. Functions have a limited scope, which I believe is an asset. This means that if you define a variable inside the function, you cannot reference that variable outside of the function.

Example

function greetings()
{

echo “Greetings”;

}
greetings();

Result

Greetings

Here, we have a function called greetings. After we define the function, we called the function with greetings();. Pretty simple, huh? Now, let’s make our functions even more useful by adding arguments.

Function Arguments

Example

function sampleFunction($argument1)
{

echo $argument1;

}
sampleFunction(“Something”);

Result

Something

Woot woot! We just used a parameter. A parameter is like a variable of the function that is defined when you call the function later. We can see how it is more useful in the next example.

Example

function addingFunction($parameter1, $parameter2)
{

echo $parameter1 + $parameter2;

}
addingFunction(333,444);

Result

777

This is similar to the last example. At the end, we call our function addingFunction(). We pass in two parameters this time: 333 and 444. Where 333 is being passed into the addingFunction as $parameter1 and 444 is also passed in as $parameter2. Once they are both passed in, we echo the sum of the two parameters. In the result, you can see that echo sent back 777. The final statement that executed was more like echo 777;. Nice job!

Like I said, understanding functions is crucial to your success as a programmer.

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Facebook
Share on Google+
Google+
Share on StumbleUpon
StumbleUpon
Digg this
Digg
Tweet about this on Twitter
Twitter
Share on Reddit
Reddit

Leave a Comment

  1. Love it, managed to put together
    function calculator($no1, $limiter, $no2){
    switch($limiter){
    case "+":
    echo $no1 + $no2;break;
    case "-":
    echo $no1 – $no2;break;
    case "/":
    echo $no1 / $no2;break;
    case "*":
    echo $no1 * $no2;break;
    }
    }

    calculator(45, "/", 5);

    after putting this together, I’m sure there is a better way to do it but looks good to me haha

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.