Tutorial 23: Intro to Functions


If you've made it this far, congratulations are in order! We've covered a lot of ground, and our PHP coding skills are becoming much more refined and skillful!

I'm going to go ahead and say that functions are the Meat n' Potatoes (vegetarian version: Beans n' Rice) of most programming languages; they are fundamental when cooking a tasty PHP dinner!

In PHP, there is a massive library (over 1000) of baked-in functions—pun intended—that do everything from printing text on your screen to adding information to a database, and much more!

It's good to know that there are two types of PHP functions: Built-in PHP Functions, and Custom Functions (you can write your own custom PHP functions!).

Remember echo and print? Those little guys are functions!

Important Facts about Functions

A function is a block of statements that can be used repeatedly in a program.

A function will not execute immediately when a page loads.

A function will be executed by a call to the function.

w3schools

Let's take a look at the basic syntax of a function:

function functionName() {

	// execute code

}

PHP sort() Function

Let's take a quick look at the built-in PHP sort() Function. This function allows us to sort an array in alphabetical order.

First, let's create an array:

// Custom array
$dinner = array("Meat", "Potatoes", "Beans", "Rice");

Now let's run our array through the sort() function:

// Custom array
$dinner = array("Meat", "Potatoes", "Beans", "Rice");

// Add the array as a parameter to sort() function
sort($dinner);

Now all we have to do is echo our array on the screen, using a Foreach loop:

// Custom array
$dinner = array("Meat", "Potatoes", "Beans", "Rice");

// Add the array as a parameter to sort() function
sort($dinner);

// Echo the sorted array
foreach ($dinner as $ingredient) {
    echo "$ingredient 
"; }

If coded correctly, the above will echo the array in alphabetical order:

Beans
Meat
Potatoes
Rice

If you're looking to sort your array in reverse order, you can use the PHP rsort() function. Feel free to read more about the sort function, and other sorting functions here.

We won't be covering all of the built-in PHP functions in this course, because that would take an incredibly long time. Besides, it's fun to be in a situation where you're programming and then you think "Hey! I wonder if there's a PHP function that will do this for me?" — this is why I'll leave you with the curiosity to experiment. Google is your best friend, and you may also refer to this directory.

Feel free to experiment with the above Sort Function with some PHP using the practice.php page provided in this folder.

Check out the final example
©2019 Brad Hussey