In PHP, we really don't like repeating the same code over and over. To deal with that, we already discovered loops, which let us run instructions multiple times. Now it's time to explore another essential structure: functions.
Like loops (which we covered in the previous chapter), functions help us avoid rewriting PHP code we use frequently. But where loops are kind of like simple machines that mindlessly repeat the same thing 200 times, functions are more like intelligent robots โ they adapt to what you ask them to do, and they can automate tons of everyday tasks.
What is a function?
A function is a set of instructions that performs an action and returns a value. Anytime you need to carry out a slightly complex operation that you might need again later, it's a good idea to check whether there's already a function that does it for you. And if not, you can create your own!
Picture a function like a little robot, something like this:
[I am a Function Robot ๐ค]
You have no idea what's going on inside that robot, but you can press a button and ask it to do something specific. Functions in PHP work just like that!
Talking to a function
Here's an example of the kind of "conversation" you might have with a function:
- You: Hey, function calculateCube, tell me the volume of a cube with sides of 2 cm.
- The function crunches the numbers and answers:
- This cube has a volume of 8 cmยณ.
You're giving the function an input โ a parameter โ like the side length of the cube (2 in this case). And in return, it gives you a result: 8.
2 -> [I am a Function Robot ๐ค] -> 8 3 -> [I am a Function Robot ๐ค] -> 27 4 -> [I am a Function Robot ๐ค] -> 64
Thanks to the function, you don't have to remember how to calculate the volume of a cube. Sure, in this case it's easy (just do 2 * 2 * 2), but you'll often be doing much more complex stuff โ and functions are here to save you from drowning in the math.
Now, if you only had to calculate the volume of a cube once, you could've just looked it up in a book (if you forgot the formula ๐) and typed it out by hand. But what if you needed to do it 5 times? 10 times? 100 times?
Great question! Loops also let us repeat code several times, right?
Yes, but functions can adapt based on the information you give them. In our case, you just send the side length of the cube to the function, and it gives you the answer. The info you send in is called a parameter โ an important term to remember!
I hear you! I only used a math example because it's simple and easy to understand. Don't worry โ building websites doesn't mean you'll be calculating logarithms and square roots all day. ๐
In real-world scenarios, functions are used for all sorts of things: getting the current date and time, encrypting data, sending emails, searching within text, and so much more.
Using Functions in PHP
So far we've been chatting with imaginary robot functions โ fun, but let's get back to some real, solid PHP.
Calling a function
So, how do you actually call a function in PHP? Easy โ just use its name! Like this:
<?php calculateCube(); ?>
The calculateCube function here is imaginary โ it doesn't exist (unless we write it ourselves). So don't try running this code at home just yet; it won't work. Just read through it for now to get a feel for how things work. You'll get your hands dirty soon enough.
As you can see, I just wrote the function name, followed by empty parentheses, and of course, a good old semicolon. That's how you call a function โ but in this example, we're not sending it any information.
Some functions can work without parameters, but they're pretty rare. In the case of calculateCube, it doesn't make sense to call it without telling it the side length of the cube!
If we want to send a parameter โ a number, a string, a boolean, whatever โ we just write it between the parentheses:
<?php calculateCube(2); ?>
Now the function knows it needs to do its thing with the number 2.
Sending multiple parameters
Many functions can accept more than one parameter. If that's the case, just separate them with commas:
<?php imaginaryFunction(47, 'Red', true, 15.8); ?>
This function receives 4 parameters: 47, the string "Red", the boolean true, and the float 15.8. Getting the return value from a function
Okay, so now we know how to call a function and send it parameters. But how do we get something back if the function returns a result?
There are two types of functions:
- Functions that don't return anything (but can still perform actions).
- Functions that do return a value.
If a function doesn't return anything, you don't need to do anything fancy. Just call it, let it do its thing, and move on.
But if the function returns a value โ like calculateCube should โ you can catch it using a variable, like this:
<?php $volume = calculateCube(2); ?>
Let's break this down. Two things happen here, right to left:
- calculateCube is called with the parameter 2.
- Once it finishes, it returns a value, which is stored in the variable
$volume
.
So, after this line runs, $volume
will hold the value 8.
PHP's Ready-to-Use Functions
PHP comes packed with hundreds and hundreds of built-in functions. The official PHP website has a full list of them, neatly organized by category.
These functions are super handy and, honestly, there are just so many of them! In fact, that's one of PHP's biggest strengths โ its functions are incredibly versatile and cover just about everything you could need. I've noticed that almost every time I get ready to write my own function, I realize... it already exists. ๐
Here's a little teaser to get your mouth watering:
- A function that finds and replaces words in a variable
- A function that uploads a file to a server
- A function that creates image thumbnails
- A function that sends an email using PHP (perfect for building a newsletter!)
- A function that edits images โ adds text, draws lines, rectangles, etc.
- A function that encrypts passwords
- A function that returns the current date and time
- ...and tons more!
Most of the time, you'll need to pass in some parameters to tell the function what to work on.
Let's take a quick look at a few example functions to get you familiar with how they work. We obviously can't go through all of them (remember, there are hundreds!), but once you get the hang of these and start exploring the PHP documentation, you'll be off to the races! ๐
We'll check out some string manipulation functions, and one that gives you the current date. Just a few samples to help you get comfy with using functions.
๐งต Working with Strings
There are loads of functions for manipulating text. Here are a few to show you how useful they can be:
strlen
This function returns the length of a string โ in other words, how many characters it contains (spaces included). Example:
<?php $phrase = 'Hello Noobs! I'm a sentence!'; $length = strlen($phrase);echo 'The sentence below has ' . $length . ' characters:<br />' . $phrase; ?>
str_replace
str_replace
replaces one string with another. Check it out:
<?php $my_variable = str_replace('b', 'p', 'big boss bob');echo $my_variable; ?>
It takes three parameters:
- The string you're looking for โ in this case, we're replacing all "b"s
- The string you want to replace it with โ here, we're using "p"
- The string where the search-and-replace should happen
Result? You get: pig poss pop
๐
str_shuffle
Want to scramble a string for fun? Use this!
<?php $string = 'This string will be shuffled!'; $string = str_shuffle($string);echo $string; ?>
Give it a try yourself โ it's oddly satisfying ๐
strtolower
strtolower
turns all the letters in a string to lowercase:
<?php $string = 'WHY ARE YOU SHOUTING???'; $string = strtolower($string);echo $string; ?>
And yes, there's also strtoupper
โ which does the reverse: lowercase โ UPPERCASE.
๐ Getting the Date
Time to meet the date function! (Easy to remember, right?) This one gives you all sorts of date and time info. Here are the main format characters you'll use:
Format | Meaning |
---|---|
H | Hour |
i | Minute |
d | Day |
m | Month |
Y | Year |
If you want to get the current year, just pass 'Y' to the function:
<?php $year = date('Y'); echo $year; ?>
Want the full date and time? Let's level up:
<?php $day = date('d'); $month = date('m'); $year = date('Y');$hour = date('H'); $minute = date('i');
echo 'Hello! Today is ' . $day . '/' . $month . '/' . $year . ' and it's ' . $hour . 'h' . $minute; ?>
Boom! Date and time, just like that.
Creating Your Own Functions
Sure, PHP gives us an enormous number of built-in functions (have I said that enough yet?), but sometimes you'll need to roll up your sleeves and write your own.
If you're doing something a bit complex โ and especially if you'll need to do it repeatedly โ it's a good idea to wrap it in a function. It'll save you time and keep your code clean.
We're going to learn function creation with two examples:
- Greeting a visitor by name
- Calculating the volume of a cone
1st Example: Say Hello to Your Visitors
Saying hello to every visitor by hand is a pain, right? Let PHP do it for you!
Here's what not to do:
<?php $name = 'Bob'; echo 'Hello, ' . $name . '!<br />';$name = 'Pat'; echo 'Hello, ' . $name . '!<br />';
$name = 'Jace'; echo 'Hello, ' . $name . '!<br />'; ?>
That gets old fast. Let's build a function to do it automatically:
<?php function sayHello($name) { echo 'Hello, ' . $name . '!<br />'; }sayHello('Neo'); sayHello('Yoda'); sayHello('Frodo'); sayHello('Morpheus'); sayHello('Gandalf'); sayHello('Jar Jar'); sayHello('Santa Claus'); ?>
At the top, we define the function โ its name and what it does. This doesn't run the function yet โ it just tells PHP: "Hey, from now on, sayHello
is a thing."
To define a function, you use function, then the function name (sayHello
here), followed by parentheses containing any needed parameters โ in this case, a name to greet.
Notice there's no semicolon at the end of that line โ it's not an instruction, it's a declaration.
Then you have curly braces {}
to mark the start and end of the function's code. Inside, we just have a simple echo. (But in real life, functions can contain way more logic.)
Once the function's created, you don't have to touch it anymore โ just call it by name and pass in the needed info (like the name to greet). And this time you do need the semicolon, since you're running an instruction.
Example:
<?php sayHello('Neo'); ?>
Now go ahead, create a page with this function and greet whoever you want! It works! ๐ (Well, obviously... but still! ๐)
2nd Example: Calculating the Volume of a Cone
Alright, let's take it up a notch.
Our sayHello function didn't return anything โ it just printed something. Now we'll make a function that returns a value.
Let's say we want to calculate the volume of a cone. You give the function a radius and a height, and it returns the volume.
First, a quick math refresher. Remember how to calculate the volume of a cone? No? Me neither. ๐
Here's the formula:
volume = radius ร radius ร 3.14 ร height ร (1/3)
You could do it like this every time:
<?php // Volume of a cone with radius 5 and height 2 $volume = 5 * 5 * 3.14 * 2 * (1/3); echo 'The volume of a cone with radius 5 and height 2 is: ' . $volume . ' cm<sup>3</sup><br />';// Volume of a cone with radius 3 and height 4 $volume = 3 * 3 * 3.14 * 4 * (1/3); echo 'The volume of a cone with radius 3 and height 4 is: ' . $volume . ' cm<sup>3</sup><br />'; ?>
But that gets repetitive fast. Let's write a function instead!
<?php // The function that calculates the cone volume function coneVolume($radius, $height) { $volume = $radius * $radius * 3.14 * $height * (1/3); return $volume; }$volume = coneVolume(3, 1); echo 'The volume of a cone with radius 3 and height 1 is ' . $volume; ?>
Check out the line: return $volume;
. That's what sends the result back to whoever called the function.
If you wrote return 15;
, it would always return 15 โ not very useful, but go ahead and try it! ๐
Since the function returns a value, we store it in a variable:
<?php $volume = coneVolume(3, 1); ?>
Then we can use echo to display it.
The possibilities with custom functions are almost endless. You probably won't need a cone volume calculator in real life (unless you're a geometry fanatic ๐), but this is just to help you understand how functions work and why they're useful.
If you understand the code, great! If you try creating your own test functions, even better.
You now know the essentials of PHP functions! Of course, there's more to learn โ but you've got the foundation down. And speaking of foundations, you're no longer a total PHP noob โ you're nearly done with the basics! ๐
Enjoyed this PHP & MySQL course?
If you liked this lesson, you can find the book "How to Build a Website in HTML and CSS" from the same authors, available on SiteRaw, in bookstores and in online libraries in either digital or paperback format. You will find a complete PHP & MySQL workshop with many exclusive bonus chapters.