In this guide, we would look at functions in PHP...so...first
Intro To Functions
Functions are modular building blocks for creating powerful and modular scripts, using function makes it easy to isolate a code since it would be packaged up into a single unit, and you can then call the unit whenever and wherever it is needed.
If you've been following my previous guide on PHP, then you've seen function in action, an example of a function is strtolower(), strtoupper(), etc. Here are the previous guides if you are interested:
If you are wondering why functions are super useful, here are some uses:
- It can help make your script more readable and avoid writing the same code multiple times, this is call re-usability, once a function is coded, it can be applied multiple times in the script. You can also port it to another script.
- Instead of sifting through long spaghettis of code, functions make it easier to figure out what a particular part of code is supposed to do.
The syntax for defining a function:
>?php
function function_name($arg1, $arg2, ...) {
// statements;
}
Definition starts with function, the function name with parenthesis which enclose our argument list (the arguments are optional), these are the arguments the function is going to accept, make sure they are separated by comma as you can see in the example above.
The statement is the meat of the function, it contains all of the code you want the function to do, and the good thing about using a function is that the code would be reusable, you would be able to call the function from a lot of different places.
Below is an example of a function that greets our users:
<?php
function greet() {
echo "Hello World <br>";
}
By default, the above isn't going to do anything, well, we only defined the function and added an echo statement, you might not realize it, but what we actually did is stored the functions in memory for later use, so, whenever you want to use the function, you need to call it, so, here is how it is done below:
<?php
function greet() {
echo "Hello World <br>";
}
greet(); # Calling The Function greet
#
# Ouput:
#
Hello World
As you can see, we called the function greet, it then prints "Hello World" make sure the parenthesis is there, otherwise it won't work, so, make sure you have greet();
and not greet;
As it is now, we are mainly calling our function which enclose an echo statement, now, let's try a function with an argument:
<?php
function userinfo($name) {
echo "My Name Is {$name}";
}
In the above example, I added one argument $name, that is ready available in the function block which contains an echo statement, so, what happens here is that, whatever the user passes into the function userinfo(), it would be accessible inside the function, which would then make it executes whatever is inside the function.
To make use of this, you pass a string into the function, the below is an example:
<?php
function userinfo($name) {
echo "My Name Is {$name} <br>";
}
userinfo("James"); # Calling The Function userinfo
#
# Ouput:
#
My Name Is James
You see how flexible that is, that is one of the main advantage of using a function, you can reuse the code, and make your life easier.
Also, you always don't have to pass in a string, you can pass in a variable that contains the string, e.g:
$myName = "James";
userinfo($myName); # Calling The Function userinfo
The functions assign whatever is in the variable $myName, into the $name which is the function argument, so, it doesn't have to match.
Note that once a function is defined, you can't redefine it, it only gets defined in one spot, but you are free to define more functions as you see fit, just make sure not to use the same function name.
Let's try a function with more than one argument:
<?php
function fix_names($n1, $n2) {
$n1=ucfirst(strtolower($n1));
$n2=ucfirst(strtolower($n2));
echo "Your Full Name Is: $n1 $n2<br>";
}
The above function clean up the user Full Name, so, even if the user passes a string like so: "saMueL", it would get converted to "Samuel", that is made possible by the ucfirst()
and the strtolower()
function, the way it works is that the strtolower()
function would first convert everything to lowercase, we then use ucfirst()
to convert the first character to uppercase.
As you can see we are using two arguments, so the user would need to supply two parameters when calling the function:
<?php
function fix_names($n1, $n2) {
$n1=ucfirst(strtolower($n1));
$n2=ucfirst(strtolower($n2));
echo "Your Full Name Is: $n1 $n2<br>";
}
fix_names("chARles", "babBaGe"); # Calling The Function fix_names
#
# Output:
#
Your Full Name Is: Charles Babbage
Return Values from A Function
Well, we've seen a bit of flexibility with using a function, but really, all we've done is basically printing out the result of whatever gets passed into the function. What if we would like to get a result from the function, and then decide what to do with that result ourselves, so, in that scenario, we don't want the function to output the result for us, but instead we want to choose when to do the output, to do that, we need to understand how to return values from a function.
Typically, the output produced by a function would practically go on to the screen when called, but you can actually get it to go somewhere else, you can send the output of a function to another function, another interesting thing you can do is to return the output of a function, and store it in a variable, which you can then use later for further processing.
Here is how it works:
<?php
function multiply($n1, $n2) {
$total = $n1 * $n2;
return $total;
}
echo multiply(3,4);
#
# Output:
#
12
Instead of telling the function to echo the result, we return the value to whatever control is calling it, that is the reason we are able to use the echo outside of the function, you can as well store the returned value into a variable, and perform more processing on it, e.g:
<?php
function multiply($n1, $n2) {
$total = $n1 * $n2;
return $total;
}
$returned = multiply(3,4);
echo $returned + 5;
#
# Ouput:
#
17
You can see how this gives us more flexibility, when the function returns a value, it immediately exit the function, so keep that at the back of your mind.
Return Multiple Values from A Function
A function can only return a single value, it would be cool to return multiple values, maybe by calling return 1, return 2, etc, unfortunately, it doesn't work that way, but there is a way we can actually return multiple values from a function, the way we can do this is to think of a single entity that can hold more than one thing, and as you might have guessed, it is an array, we can return an array, and that can hold more than one value for use, the below is an example:
<?php
function math($n1, $n2) {
$multiply = $n1 * $n2;
$add = $n1 + $n2;
return array($multiply, $add);
}
$math_array = math(5,5);
echo "Mult: " . $math_array[0] . "<br>";
echo "Add: " . $math_array[1] . "<br>";
#
# Ouput:
#
Mult: 25
Add: 10
I won't go over how an array works, so, if you don't know how an array works, here is a guide on that: Arrays in PHP.
We use the array as a mechanism to return more than one value from the function, and that is because arrays are built to handle the collection of objects
Another way you can break down the array returned from a function is to use the list() function, it is used to assign a list of variables in one operation, so, instead of relying on a single variable as we've done above, we can use the list to break them down, e.g:
<?php
function math($n1, $n2) {
$multiply = $n1 * $n2;
$add = $n1 + $n2;
return array($multiply, $add);
}
list($mult, $add) = math(5,5);
echo "Mult: " . $mult . "<br>";
echo "Add: " . $add . "<br>";
#
# Output
#
Mult: 25
Add: 10
You can see how less clunky that is, it is not really hard to understand, the way it works is that it takes the values from the function arguments, in our case it is: math(5,5)
, and then assigns them to the argument in the list, which in our case it is: $mult, and $add, so, by doing that, we can then make use of it, which we did below the list line, here:
echo "Mult: " . $mult . "<br>";
echo "Add: " . $add . "<br>";
This just makes things a bit more easier, instead of relying on the array indexes.
Setting Default Argument Values
As it is now, there is no way to handle the scenario when we do not pass any argument to the function, to fix this, we can set default argument values for function parameters, this way, when we do not pass any arguments, PHP will use the default set value for this parameter in the function call.
To do this, you simply do:
<?php
function color($col1="red",$col2="blue") {
return "The color you choosed are: {$col1} and {$col2}. <br>";
}
echo color();
#
# Output:
#
The color you choosed are: red and blue.
As you can see, the default filled the spot if we did not pass an argument, but the moment you pass an argument, it would be replaced.
Also, if you have, say 4 arguments, and you want to make 2 out of 4 args optionally, then you need to make sure the required values are listed first and the optional ones, I mean the one that has a default value can be listed at the end of the arg list
Variable Scope
Variable scope refers to the visibility of variables, meaning which parts of your code can see or use the variable, there are mainly two type of variable, and that is the local and global variable scope.
A variable created inside the function is by default only accessible in the function, you won't be able to use such variable outside of the function, which is why we say such variable is local to the function, let's see an example of a global and local variable scope:
<?php
$name = "Paul"; # Global Variable
function scope() {
echo $name; # reference to local scope variable
}
scope();
The above will not produce any output, and that is because the echo statement in the function refers to a local version of the $name variable, which hasn't been assigned a value within the scope. It doesn't know of the variable defined in the global scope.
Consider the following example:
<?php
$name = "Outside Variable"; # Global Variable
function scope() {
$name = "Local Variable"; # Local Variable
echo $name; # reference to local scope variable
}
scope();
#
# Output
#
Local Variable
That shouldn't be a surprise, the echo statement is referencing the $name variable that is local to the function, which is the reason why the output was "Local Variable", in other words, the echo statement is been used inside the function, and when you call the function, it simply reference the $name variable inside the function, now, consider the following example:
<?php
$name = "Outside Variable"; # Global Variable
function scope() {
$name = "Local Variable"; # Local Variable
}
echo "$name <br>";
scope();
echo "$name <br>";
Here are the steps we took in the above code:
- We declared a global variable $name
- We also declared an identical variable $name that is local to the function
- We then printed the result of the variable when the function is not called, what do you think the result would be?
- We called the function, and lastly...
- We printed the result of the variable, in the hope that it might now be visible, so, what do you think the result of this would be?
The result of both echo statement is "Outside Variable", why though? The variable inside the function won't be visible outside the function even if you call the function, you can test this by using a new name entirely in the function, but that is not the point. The point is, how do you make a variable a global variable, visible in a function? To do that, you need to declare a global variable, see an example:
<?php
$name = "Outside Variable"; # Global Variable
function scope() {
global $name;
$name = "Local Variable"; # Local Variable
}
echo "$name <br>";
scope();
echo "$name <br>";
#
# Output
#
Outside Variable
Local Variable
As you can see, the moment we call the function, we are able to make use of the variable, it gave us access to it in the function, that was the reason, we are able to change the assignment from "Outside Variable" to "Local Variable". Well, this isn't something you wouldn't want to do in a real life project, so, you might just be better off using an arguments instead as we've done above instead of calling the function and then echoing.
Here is another example:
<?php
$n1 = 5;
$n2 = 5;
function sum()
{
global $n1, $n2;
$n2 = $n1 + $n2;
}
sum();
echo $n2;
#
# Output:
#
10
You can see how we are able to use the global variable in our function superbly, offcourse, you should only do this if you want to make use of the variable that is outside of a function, and you might not even need that most of the time, the point is, you need to understand the difference between the two.