PHP
PHP TUTORIALPHP IntroductionPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP OutputPHP Data TypesPHP Type CastingPHP 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.

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.

You will learn about the other built-in functions step-by-step in this tutorial.

PHP User-Defined Functions

The function declaration starts with the 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 the same as variable naming except for the $ sign at the beginning. Functions do not have the $ sign.

PHP Declaring User-Defined Functions

Let's create our first function.

Note: In PHP, parentheses are used to call a function.

PHP User-Defined Function Example


<?php
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 the function.

Let's see an example.

PHP Function Arguments Example


<?php
function myName($name) {
	echo 'My name is ' . $name; 
	echo '<br>'; // line break
} 
myName('Joe'); 
myName('Adam');
myName('David');

Run Example ››

Functions can have multiple arguments.

PHP Function Multiple Arguments Example


<?php
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


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


Run Example ››

In the above example,

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

PHP Passing Arguments By Reference Example


<?php
function changeName(&$name) {
	$name .= ' Developer';
	echo 'Inside the function: ' . $name . '<br>'; // outputs "Hyvor Developer"
}
$rootName = 'Hyvor';
changeName($rootName);
echo 'Outside the function: ' . $rootName; // now it's 'Hyvor Developer'


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


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

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

Run Example ››

PHP Function Arguments - Type Declaration

Type declaration (also known as type hinting) can be used to specify a data type for each argument. PHP will throw an error on incorrect data types. The data type should be added before the argument to specify type declaration for it.

PHP Functions - Type Declaration in Arguments


<?php
function myDetails(string $name, int $age, string $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');
myDetails('John', 'N/A', 'Australia'); // this will cause an error

Run Example ››

Valid Types For Type Declaration

Type Description Min PHP Version
array The argument must be an array 5.1.0 Run Example ››
callable The argument must be a callable (function or method) 5.4.0 Run Example ››
int The argument must be an integer 7.0.0 Run Example ››
float The argument must be a float 7.0.0 Run Example ››
bool The argument must be a boolean 7.0.0 Run Example ››
string The argument must be a string 7.0.0 Run Example ››

PHP Functions - Returning

There are two uses of return statements.

PHP Functions - Returning Values

PHP Functions - Returning Values Example


<?php
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 ››

PHP Functions - Type Declaration for Returning Values

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

The types are as same as the types in argument type declaration. The type should be specified after the function name, adding a semicolon :.

PHP Functions - Returning Values of a Specific Data Type


<?php
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


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

Run Example ››

PHP Anonymous Functions

Functions without a name are called anonymous functions (or closures). They are really helpful to send callback arguments into functions.

PHP Anonymous Functions Example


<?php
function callFunc($callback) {
	$x = rand();
	$callback($x);
}
callFunc(function($number) {
	echo $number;
});	

Run Example ››

In the above example, we specify the first parameter of callFunc() function as an anonymous function.

True, this can be tricky for you. We will use anonymous functions with more examples in the later chapters.