Learning PHP: Part 3: Functions

Learning PHP

PHP: Hypertext Preprocessor (PHP) is a server-side scripting language frequently used as part of web development and as a command-line tool for common tasks.


In programming terminology, a function is a set of statements. Often, but not always, a function is something that can be called and returns a value. In PHP, there are a large number of built-in functions that can be used, but new functions can also be created.

Creating Functions

Screenshot 2018-10-29 15.29.07

New functions are created in PHP using the keyword function. In PHP, like many other programming languages, functions have four parts: name, parameters, statements, and a return statement.

Name: The name of the function is what follows after the keyword function. It follows the same rules as variables. It can have letters, numbers, and the underscore. It cannot use special characters.

Parameters: The parameters of a function are what are sent into a function. Inside the parentheses, the variables listed can be used by their names.

Statements: A function can contain one or more statements. In PHP, like other programming languages, a statement is simply something that ends in a semicolon. It can be the creation of variables, the assigning of their values, or other things.

Return statement: In PHP, a return statement is optional. Functions can return values if they compute or otherwise change values. If a return statement is missing, the function will end when there are no more statements to run.

Using Functions

Screenshot 2018-10-29 15.36.22

Created functions can be called just like the other, built-in ones in PHP. Using the functions’s name and parentheses, values can be sent into the function using its parameters.

Screenshot 2018-10-29 15.40.31

When a return statement is used in a function, its result can also be saved.

Play with the example on Repl.it!