PHP TUTORIALPHP IntroductionPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP VariablesPHP ConstantsPHP OutputPHP Data TypesPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP StringsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms Finishing

PHP Functions

A function is a type of procedure or routine.
  • A function is a group of statements.
  • A function is not executed until it is called
  • A function can be called as many times as you need, in a script.

PHP Built-In Functions

PHP has thousands of built-in functions. Each of those functions is focused to perform a specific task. We have already discussed four of them.

  • echo() - to output a string
  • print() - to output a string
  • define() - to define a constant
  • var_dump() - to dump data of a variable

You will learn about these functions step-by-step in this tutorial.

PHP User-Defined Functions

The function declaration starts with function keyword. Then, the function name and arguments.

function functionName(arg1, arg2, ....) { code to be executed }

PHP Naming User-Defined Functions

Function naming is almost same as variable naming except adding a $ sign into the beginning. Functions does not have $ sign.

  • A function name should start with a letter or underscore.
  • A function name cannot start with a number.
  • Letters, numbers and underscores can be used after the first letter in a function.
  • A function name is case-insensitive (Both boom() and Boom() refers the same function.)
  • Tip: Always name functions with a name that describes the usage of the function.

PHP Declaring User-Defined Functions

Let's create our first function.

  • First, we declare the function greet() using function syntax.
  • The block of code inside the curly braces ({}) is the function code. This code is executed when we call the function.
  • Then, we call our function using its name and parentheses: greet();

Note: We always use parentheses to call a function.

PHP User-Defined Function Example

function greet() {
	$hour = date('G'); // get the hour in 24-hour format
	if ($hour < 12) {
		echo 'Good Morning';
	} else if ($hour < 17) {
		echo 'Good Afternoon';
	} else {
		echo 'Good Night';

greet(); // calling the function

Run Example ››

PHP Function Arguments

We can get different results from a function using arguments.

Function arguments are the values passed into a function. An argument is a variable inside function.

  • Arguments are defined inside the parentheses which are immediately after the function name.
  • A function can have any number of arguments, separating them with a comma.
  • A argument name has the same rules as a variable.

Let's see an example.

  • First, we declare a function named myName with one argument, $name.
  • Then, we call the function several times with different values.
  • Note the value inside the parentheses of the function call. That value is assigned to $name when the function executes.

PHP Function Arguments Example

function myName($name) {
	echo 'My name is ' . $name; 
	echo '<br>'; // line break

Run Example ››

Functions can have multiple arguments.

PHP Function Multiple Arguments Example

function myDetails($name, $age, $country) {
	echo "
		My name is $name <br>
		My age is $age <br>
		My country is $country <br><br>
myDetails('Joe', 22, 'USA');
myDetails('Adam', 25, 'United Kingdom');
myDetails('David', 30, 'France');

Run Example ››

PHP Function Arguments - Passing By Reference

By default, arguments are passed into functions by value. See the following example to understand it.

PHP Passing Arguments By Value Example

function changeName($name) {
	$name .= ' Developer';
	echo 'Inside the function: ' . $name . '<br>'; // outputs "Hyvor Developer"
$rootName = 'Hyvor';
echo 'Outside the function: ' . $rootName; // it is stil 'Hyvor'

Run Example ››

In the above example,

  • $rootName variable is set to "Hyvor".
  • Then, it is passed into changeName() function as the $name argument.
  • Inside the function, "Hyvor" is changed to "Hyvor Developer".
  • But, after executing the function the global variable $rootName still holds the value "Hyvor".

You can change the value of an argument by passing them by reference. Just prepend an & sign to the argument name in the function definition.

PHP Passing Arguments By Reference Example

function changeName(&$name) {
	$name .= ' Developer';
	echo 'Inside the function: ' . $name . '<br>'; // outputs "Hyvor Developer"
$rootName = 'Hyvor';
echo 'Outside the function: ' . $rootName; // it is stil 'Hyvor'

Run Example ››

PHP Function Arguments - Default Values

To specify a default value for an argument, just assign that with the basic assignment operator (=) in the function definition. If the argument is not provided when calling the function, this default value is used.

PHP Functions - Default Values for Arguments Example

function printNumber($number = 10) {
	echo "The number is: $number <br>";

printNumber(); // will print 10, the default value

Run Example ››

PHP Functions - Returning

There are two uses of return statements.

  • To return a value from a function.
  • To stop the execution of a function when certain condition is true.

PHP Functions - Returning Values

PHP Functions - Returning Values Example

function sum($num1, $num2) {
	return $num1 + $num2;

echo '5 + 5 = ' . sum(5,5) . '<br>';
echo '4 + 3 = ' . sum(4,3) . '<br>';
echo '8 + 1 = ' . sum(8,1) . '<br>';

Run Example ››
Since PHP 7, you can define the data type of the returning value.

PHP Functions - Returning Values with a Specific Data Type

function sum($num1, $num2) : float {
	return $num1 + $num2;
var_dump(sum(5, 2)); // float value is returned

Run Example ››

PHP Variable Functions

If a variable which contains a string has parentheses appended to it, PHP checks for a function with the same name, and will execute it. This concept is called variable functions.

PHP Variable Functions Example

function printSentence() {
	echo "My name is Hyvor Developer";
$functionName = 'printSentence';
$functionName(); // called printSentence function

Run Example ››