Home » Tutorials » PHP » Functions

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.



Link/cite this page

If you use any of the content on this page in your own work, please use the code below to cite this page as the source of the content.

  • Stewart, Suzy. "Functions". After Hours Programming. Accessed on March 16, 2024. https://www.afterhoursprogramming.com/tutorial/php/functions/.

  • Stewart, Suzy. "Functions". After Hours Programming, https://www.afterhoursprogramming.com/tutorial/php/functions/. Accessed 16 March, 2024.

  • Stewart, Suzy. Functions. After Hours Programming. Retrieved from https://www.afterhoursprogramming.com/tutorial/php/functions/.



2 thoughts on “Functions”

  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 Comment

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