Knowledge

PHP Fundamentals: Basic Functions

Published on June 11, 2014 under How-To, Web Development

Functional gears

If you’ve been following along with these PHP Fundamentals articles, then I imagine you’ve gotten the basics of PHP down. You’re printing text on pages, working with numbers, sending data in and out of databases, and you might even be using arrays to help sort data.

These are all great stepping stones, but now it’s time we get into some real meat and potatoes, and that would be functions. If you’ve ever taken an Algebra course, then you’ll recognize the term and what a function is. For those who do not, a function (in programming) is an encapsulated set of code designed to take in one or more pieces of data, process them, and then return a desired result.

Why functions?

Diagram of the idea of a functionSo why would you be in need of a function? You could imagine your need to process some text, numbers, or other data as easily doable within the one page you’re coding. Now what happens if you need to use that process over a multitude of pages? Are you ready to copy/paste that code onto every page?

Now you could recall how I showed you how to use an include to place code into a page from another file. Granted, you could do this with your coded process, but bear in mind when you run that page, it will run that script every time...thus adding load/processing time to your website. With a function, the process only runs when you tell it to. It sits and waits for the inputted data from you, thus if you don’t give any command, it won’t run.

When I redesigned Culinaria (and am currently doing a recode using Bootstrap), I made my first use of functions over several parts of the website. Whenever you see the author name on an article, it was a function that took an ID number from the article data and then went out to get the name of the author that ID applies to. Simple, but useful.

A bigger scenario was when I built a system to take a shortcode and convert it into a fully laid-out recipe. So a code placed in an article like this:

[recipe:26 image:yes]

Would then return the full recipe laid out in its tan rectangle with its image. All I do is parse that string to remove the number and the “yes” or “no” from the image parameter. Feed it through the function, and it returns the HTML. I have another big function coming that will create related links based on the tags.

Getting into functions

Now that I’ve hopefully excited you, let’s get into making functions in PHP. The basic framework of a function is as follows:

function functionName($data01,$data02) {
    
    whatever you want done in PHP
    

    return $finalResult;
}

The functionName can be anything you like, as is the same with $finalResult. The input data ($data01 and $data02) can also be named anything you wish, but should be remembered as variables of whatever is sending the data in. You don’t have to use two data pieces. One is fine, or many. The data can be strings, numbers, or even arrays.

The return statement at the end is important, as it will be the data you send back out of the function into whatever page or process you're calling the function from. Since a function is encapsulated into its own little world, it's important to leave that means for it to send output.

In terms of what happens in the function, that’s up to you. Here’s a simple example:

function whatIsMyName($personName) {
    $myNameIs = "My name is " . $personName . ".n";

    return $myNameIs;
}

$userName = "Sam";

$myNameIs = whatIsMyName($userName);

echo $myNameIs;

You could have used a web form to handle this (I did with the included example files). You would simply have the text field be named $userName and send that data to the function.

What about something more complex? Let’s try one with numbers and an array:

function findAverage($inputNum) {
    // Determine how many numbers we have in the array.
    $numCount = count($inputNum);

    // Add up all the numbers in the array
    $sum = 0;
    foreach ($inputNum as $indivNum) {
        $sum = $sum + $indivNum;
    }

    // Determine the average
    $theAverage = $sum / $numCount;

    return $theAverage;
}

$numbers = array(12,34,56,78,90);

$theAverage = findAverage($numbers);

echo "The average is: " . $theAverage . "n";

Using a database with a function

Now that you get the idea of how basic functions work, I want to send you off with one last example, because it’s inevitable you’ll want to use your database in some way with a function.

Let’s try a simple idea on matching an owner with his/her pet:

function petAndOwner($petOwner) {
global $Link;

    $Query = "SELECT petName from petFamilies Where petOwner='$petOwner'";
    $Result = $Link->query($Query);
    while($Row = $Result->fetch(PDO::FETCH_ASSOC)) {
        $petName = $Row[petName];
    }

    return $petName;
}

$petName = petAndOwner($ownerName);

echo $ownerName . " has a pet named " . $petName . ".n";

The key thing I want you to take notice is on the use of a global declaration. This is highly important, so the $Link created in your database connection script can be used universally. Without the global declaration, your function will be unable to access the database, despite that it’s included in the same page as your database connection.

That pretty much sums up the basics of using arrays in PHP. I have included example files of all you’ve seen here. Give them a shot and please ask questions if you have them.

Download example files Download the example files from this article

Tags: php fundamentals, php, functions

comments powered by Disqus