Get DevWP - WordPress Development Theme

PHP Functions

One of the best features of PHP is the fact that it has support for over a thousand built-in functions and enables developers to create user-defined functions.

What is a function in PHP?

A function is a self-contained block of code that performs a specific task. One of the many benefits of using functions is they make your code more reusable.

Here are some of the benefits of using functions in PHP

  • PHP Functions reduce the need to write the same blocks of code multiple times within the same program. You write the function one time which can include large sections of code and then you just call the function whenever you need that specific functionality in your program.
  • Functions make your code easier to maintain. As mentioned above, you write the function one time and call it whenever it’s needed but if you eventually need to make changes to the function, you only need to change it once and all changes will be applied wherever you use the function call itself.
  • You’ll see how Functions help reduce errors within your code. Since you write the function one time, if there’s an error in your code is easier to track down.
  • You can create your own library of functions that you use in multiple programs or applications.

PHP has built-in functions that handle a lot of tasks such as:

  • image processing
  • audio processing
  • credit card processing
  • string manipulation
  • working with arrays
  • text processing
  • XML manipulation
  • web services
  • session management
  • working with databases
  • math related functions
  • working with the file system
  • cryptography
  • compression
  • authentication
  • and more

PHP User-Defined functions

In this part of the tutorial I will show you how to create and invoke functions.

The Anatomy of a PHP Function

  • A user-defined function starts with the word function
  • followed by the function name itself. This is the name you choose to give it.
  • then a pair of parentheses
  • followed by the opening curly brace
  • After the opening curly brace, you would place any code that you want to be executed
  • You would then add the closing curly brace

You would then call the function anywhere in your program by using the function name with parentheses and the semi-colon.

How to Name your PHP Function?

You should name your function something that makes sense to what its intended purpose is. Be specific with your naming convention. Also keep in mind there is a list of reserved keywords that you can’t use because they’re reserved keywords by PHP.

Here is a page from the official PHP Docs you should checkout for a List of Reserved Words and also checkout the Userland Naming Guide.

Remember, a function name must start with either a letter or an underscore. As a regular expression, functions look like ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$

Let’s look at an example of a user-defined function.

Function Pseudocode

function functionName() {
//code to be executed;

You will notice we open up with function followed by the functionName() and then the open curly brace {

Then we have a comment //code to be executed; followed by the closing curly brace }

Now let’s look at a basic function that actually works.

Basic PHP Function

function hi() {
	echo 'Hello world!';
hi(); // call the function

In the example above, we named our function hi() and inside the opening and closing curly brace we have echo ‘Hello world!’;. Finally outside of the closing curly brace we call the function with hi(); // call the function which outputs to the front end Hello World!.

PHP Functions with Arguments a.k.a. Parameters

You can specify arguments when you define your function. Arguments are specified in between the function’s parentheses. You’re able to add as many arguments as you want, just remember to separate each one with a comma. Arguments are just like variables which act as placeholders.

Note: Arguments are evaluated from left to right.

Technically, an argument is a value that you pass to a function and a parameter is the variable within the function that receives the argument. That being said, the terms argument and parameter are interchangeable.

Let’s look at a user-defined function with some arguments.

Here’s a Function with Arguments/Parameters Pseudocode

function myFunc( $firstParameter, $secondParameter ) {
	// Code to be executed

As you can see from the Pseudocode example above, the only differece was we added two Arguments in the form of Variables $firstParameter, $secondParameter. Each parameter is separated by a comma and you can have just one parameter or as many as you want.

PHP Function with Arguments/Parameters – Working Example

// Let's define the function
function sum( $num1, $num2 ) {
	$sum = $num1 + $num2;
	echo "The sum of $num1 plus $num2 is = $sum";

// Let's call the function
sum( 13, 15 ); // the output is "The sum of 13 plus 15 is = 28"

In the code example above, we have two parameters $num1, $num2 and inside the opening and closing curly braces we have a variable called $sum which is assigned the value of $num1 + $num2; and then we echo out a string which says what the the total of both variables added together is.

Note: both variables are placeholders for what will actually be used when you call the function sum() with its actual individual values.

Here’s a Function with Optional and Default Arguments/Parameters

You can also have default values for arguments as demonstrated below. Just make sure your arguments with default values are placed after any non-default arguments.

function fullName( $fname, $lname = "Rivers" ) {
	echo "$fname $lname <br>";

fullName( "Jane", "Doe" );
fullName( "Jill" );
fullName( "John", "Robertson" );
fullName( "Paul" );
fullName( "Jorge", "Smith" );

As you can see from the code example above, we have two arguments $fname, $lname = “Rivers” and $lname has a default value. Outside the closing curly brace, we call the function several times and the result is: Jane Doe, Jill Rivers, John Robertson, Paul Rivers and Jorge Smith.

Passing Arguments by Reference

By default function arguments are passed by value which means if it’s changed inside the function, this doesn’t impact or change the value outside the function. If you want to have it change the value outside the function, you would have to pass the argument by reference.

Passing an argument by reference is done by prepending an & to the argument name in the function definition.

Let’s look at an example below which first demonstrates passing by reference and then by value.

// pass by reference example
function multiply( &$num ) {
	$num *= $num;

	return $num;

$number = 10;
echo $number; // Outputs: 10
echo '<br>';
multiply( $number );
echo $number; // Outputs: 100
echo '<br>';
echo multiply( $number ); // Outputs 10000

// pass by value example
function multiply2( $num2 ) {
	$num2 *= $num2;

	return $num2;

$number2 = 10;
echo $number2; // Outputs: 10
echo '<br>';
multiply2( $number2 );
echo $number2; // Outputs: 10
echo '<br>';
echo multiply2( $number2 ); // Outputs 100

If you notice in the first code example above we pass by reference with the ampersand &. This means the value will be changed.

  • First we echo out the value of $number which is 10
  • then we use our multiply($number); function which changes that actual value in memory
  • and then we echo out the variable $number again and it outputs 100 which means the original value was changed
  • then we echo out the function multiply($number); and this time it’s value is 10000

In the second code example we pass by value which is the default way PHP handles it and let’s see how that breaks down.

  • First we echo out the value of $number2 which is 10
  • then we use our multiply2($number2);
  • and then we echo the variable $number2 and it still outputs the value 10
  • then we echo out the function multiply2($number2); and this time it’s value is 100

Hopefully that shows you the difference between passing an argument by reference vs by value. It can take a minute to wrap your head around it so definitely copy the code and change the values so you can get a solid understanding of how this works.

Return a Value from a PHP Function

In the examples above, we used echo inside our function. We can also use return.
You return a value by using the optional return statement.

Any type supported by PHP can be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from where it was called.

// Defining function
function newSum( $num1, $num2 ) {
	return $num1 + $num2;

$total = newSum( 13, 15 );
$total2 = newSum( 5, 4 );
echo $total . '<br>';
echo $total2 . '<br>';

As you can see in the code example above, inside the function we return the result of $num1 + $num2. Outside of the function, we create two variables and use different values to be added. Then we echo out those variables.

Variable Scope in PHP

There are two scopes for variables in PHP. Global Scope and Local Scope. When a variable is declared outside a function, it’s considered global which means it can be used anywhere in the project except inside of functions. When a variable is declared inside a function it has local scope which means the variable is only usable inside that function.

$varscope = 1; // global scope

function scopeTest() {
	echo $varscope; // reference to local scope variable. Generates an Undefined Variable error

scopeTest(); // doesn't output anything

You can get around this by using the global keyword like so.

$varscope2 = 1; // global scope

function scopeTest2() {
	global $varscope2;
	echo $varscope2;


PHP Built-In Functions

As mentioned earlier, PHP has over 1,000 functions that have been created to make your life as a developer easier. While I can’t demo them all in this one tutorial, I will show you some helpful functions and how you can work with them.

Below we will create a function called lower_case() and give it an argument of $n1. Then inside the function we will use the strtolower() function which is built into PHP to force all letters to lower case. This is helpful if someone fills in a name with all uppercase letters.

function lower_case( $n1 ) {
	$n1 = strtolower( $n1 );

	return $n1;

$lc_name = lower_case( "JIMMY" );
echo $lc_name;
echo '<br>';

// you could also just do this
echo strtolower('jOHNnY');


Next we create a function called upper_case() with an argument of $n1. Then inside the function we use the PHP built-in function ucfirst() to make sure the first letter in the string is upper cased. We use the variable $lc_name from the previous example.

function upper_case( $n1 ) {
	$n1 = ucfirst( $n1 );

	return $n1;
// in this part, we take the variable $lc_name from the example above and use it below
echo upper_case( $lc_name );
echo '<br>';

// you could also just do this
echo ucfirst('johnny');

What’s cool about PHP is you can nest functions inside one another. Basically the way PHP will process this is from the inside out. Let’s combine the two examples above into a more condensed version with the same end result.

function fix_names( $n1, $n2, $n3, $n4 ) {
	$n1 = ucfirst( strtolower( $n1 ) ) . "<br>";
	$n2 = ucfirst( strtolower( $n2 ) ) . "<br>";
	$n3 = ucfirst( strtolower( $n3 ) ) . "<br>";
	$n4 = ucfirst( strtolower( $n4 ) ) . "<br>";

	return $n1 . $n2 . $n3 . $n4;

echo fix_names( "dEbra", "JaSON", "kELLy", "SMITH" );

In the code example above we first use strtolower() on $n1 which makes all characters lowercase and then use ucfirst() on the result of strtolower() which will uppercase the first character.

The Takeaway

PHP is a very powerful server side coding language and both user defined functions and built-in functions give you a lot of control on how you process data. There are thousands of built-in functions that handle a variety of tasks and if you can’t find one that meets your needs, then you can code your own.

In upcoming tutorials I will demonstrate more built-in functions.

View Our Themes