Functions in PHP

In this article you will be able to learn why functions are so useful compared to plain code, but you can also learn how to use functions, how to feed them with arguments and get values back, and how to assign function values to variables.


Edited: 2018-01-20 16:56

The use of functions is one of the first steps towards organizing your code. You can think of functions as independent machine parts, where each function has it's own purpose. Functions help you create code that is more maintainable and reusable than plain code and build-in native PHP functions.

When you have learned how to use functions, the next step would be to learn object orientated programming (OOP), the sooner you learn this the better.

One of the main reason that functions themselves are so useful, is that they allow you to reuse "blocks" of code throughout your application, eliminating the need to re-write the same code over and over. It is also easier to maintain, if you later find a bug or if you just need to update the code, you only need to update it one place in your source code rather than hundreds.

User-defined functions work similar to the build-in functions in PHP. Typically you pass a number of input values (called arguments or parameters) and then you get a value back:

function mynewfunction($argument1, $argument2, $argument3)
    $output = $argument1 . ' and ' . $argument2 . ' and ' . $argument3;
    return $output;

When making new functions, use the function keyword, like done above, followed by the name of the function, and parentheses containing the optional parameters of the new function.

PHP parses the entire file before execution, so you do not have to declare a function before using it. In other words, you could place all functions in the end of your file, and call them before they are declared. I.e.:

function mynewfunction() {echo 'hallo';}

echo '<br>hallo again'; 

// output > hallo<br>hallo again

It is, however, by convention, considered a best practice to declare functions in the top of the script, usually inside included files.

Function parameters

Function parameters (or arguments) are optional input parameters that you can access inside the function. They are often integers (numbers) or text (strings), but you can also use other types. Below is a very simple example function which is adding two numbers, and returning the value:

function my_plusser($number1, $number2) {
  $output = $number1 + $number2;
  return $output;
my_plusser(5, 5); // 10

It does not matter how numbers are passed to a function, they can be passed as either strings or numbers, but it is a good practice to pass numbers as numbers since it can avoid confusion.

You work with strings by encapsulating the input in either double or single quotes. I.e.:

function user_info($first_name, $last_name) {
  $output = 'My first name is: "' . $first_name . '", and my last name is: "' . $last_name . '".';
  return $output;
user_info('Keith', 'Stonehenge'); // My first name is: "Keith", and my last name is: "Stonehenge".

Not also that we used single quotes in this example, this is because double quotes allow the inclusion of variables, which we do not specifically need for this example.

When calling a function with arguments, one can also use variables as arguments. I.e.:

$first_n = 'Keith';
$last_n = 'Stonehenge';

user_info($first_n, $last_n); // Same as before

Variables declared inside a function will only be accessible locally in that function. The same goes for arguments that you pass in your function call. So you may want to name the variables outside functions a little different from those inside, to avoid confusion.

Setting default values for function parameters

Sometimes it may be useful, to be able to leave out certain parameters in a function call. This is where default values comes in. To make one or more of your parameters have a default value, the equals sign followed by a value may be used.

When setting default values for function parameters, quotes are only for needed for strings. I.e.:

 function user_info($no_default, $first_name='Keith', $age=20) {
  $output = 'My first name is: "' . $first_name . '", and my age is: "' . $age . '".';
  return $output;
user_info($first_n); // My first name is: "Keith", and my age is: "20".

All parameters without a default value must come before those with default values, both for user-defined functions and for native PHP functions. To overcome this problem, one can use "faked" named parameters.

Using named parameters

Named parameters does not yet exist in PHP, and might not make it into PHP ever. What you can do is to use an associative array as a parameter, and then access the items via their key name. I.e.:

user_info($input) {
  $output = 'My name is: "' . $input['first_name'] . ' and my last name is: "' . $input['last_name'] . '"';
user_info(array('first_name' => 'Keith', 'age' => 20, 'last_name' => 'Stonehenge'));

Alternatively, you can also build the array outside of your function call. I.e.:

$user_info_args = user_info(array('first_name' => 'Keith', 'age' => 20, 'last_name' => 'Stonehenge'));

The most readable method is to assign each array key separately:

$user_info_args = array();
$user_info_args['first_name'] = 'Keith';
$user_info_args['last_name'] = 'Stonehenge';
$user_info_args['age'] = 20;



Tell us what you think:

  1. The best way to deal with a trailing question mark is probably just to make it a bad request, because it is a very odd thing to find in a request URL.
  2. This happens when trying to access methods on objects that are not instantiated. Always check if an object is instantiated before trying to use it.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. How to determine an optimal value for pm.max_children and related php-fpm settings for your server and web applications.
  5. PSR-1 does not permit underscores for method names, but it probably should. Also, class names most use StudlyCaps.

More in: PHP