PHP Function

Functions in PHP are similar to those in other programming languages like Java. And some new features are introduced such as arrow functions (Since PHP 7.4). Here we will introduce PHP function definition, arguments, returning values, variable functions, anonymous functions as well as arrow functions.

Function definition

A function definition in PHP looks like:

function foo( $arg1, $arg2, /* ..., */ $argn ) {
    return 'I am a function.';

// or with type declarations (argument, returning value)

// argument type declaration
function sum( float $a, float $b ) {
    return $a + $b;

// returning value type declaration
function sum( $a, $b ): float {
    return $a + $b;

// type declaration of argument and returning value
function sum( float $a, float $b ): float {
    return $a + $b;

// nullable returning type decalration 
// It return a string or null.
function get_name(): ?string {
    if ( isset($_GET['name'] ) ) {
        return $_GET['name'];
    } else {
        return null;

A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

Function arguments

Except the normal arguments, PHP function arguments support reference arguments, default argument values and variable-length arguments.

In PHP, a function is type of callable, so it is able to pass a function as an argument that you’ve seen in PHP Type.

  • In variable functions part, you will see how to pass a function as an argument.

  • In anonymous functions part, you will see how to pass an anonymous function (callback) as an argument.

Reference arguments

Different from function arguments passed by value (if the value of the argument within the function is changed, it does not get changed outside of the function), arguments passed by reference allow a function to modify its arguments.

function append_extension( &$str )
    $str .= '.csv';

$name = 'test';
append_extension( $name );
echo $name; // test.csv

Default argument values

The type of default argument value in PHP can be literal value or a complex

# A string as a default argument value.
function append_extension( $str, $ext = '.csv' )
    return $str .= $ext;

echo append_extension( 'data' );  // data.csv
echo append_extension( '.json' ); // data.json

# An array as a default argument value.
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
    $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
    return "Making a cup of ".join(", ", $types)." with $device.n";
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");


The default value must be a constant expression, not a variable.

Returning values

Use return statement to return values. In PHP, if there are multiple values needed to be return, return an array and use a list to receive them when calling the function. And you can return a reference variable.


If the return is omitted the value NULL will be returned.

Return multiple values

A function can not return multiple values, but you can return an array to achieve the similar results.


// Return multiple values as an array

function split_email ( $email ) {
    $pos = strpos( $email, '@' );
    if ( $pos !== false ) {
        return array( substr( $email, 0, $pos), substr( $email, $pos + 1 ) );
    } else {
        return array( $email, null );

list( $user, $domain ) = split_email( '' );
echo $user;   // john
echo $domain; //

The list allows you to just get some of the elements.

// Just get the first element
list( $user ) = split_email( '' );
echo $user;  // lily

Return a reference variable


Variable functions

Variable functions are those functions that are used as variables with type of callable, therefore they are more like function variables.


function func1() {
    echo 'func1';
$f = 'func1';
$f(); // call func1()

function func2( $str = '') {
    echo $str;
$f = 'func2';
$f(); // cal func2()

// class functions as variables

class MyClass {
    function myMethod() {
        echo 'I am myMethod';

    static function myStaticMethod() {
        echo 'I am myStaticMethod!';

$f = array( 'MyClass', 'myMethod' );
$f(); // prints "bar"
$f = array( new MyClass, 'myMethod' );
$f(); // prints "baz"
$f = "Foo::bar";
$f(); // prints "bar" as of PHP 7.0.0; prior, it raised a fatal error

Anonymous functions

Anonymous functions are often being used as callback functions. In PHP, they are implemented using Closure class.


# Example 1: Pass an anonymous function as a parameter

# array_map() accepts a function and an array as its parameters. It calls the function for each value in the array and return an new array with each result as its element.
$new_numbers = array_map(function( $v ){ return $v * 2; }, [1, 2]);

# Example 2: Return an anomymous function

function get_handler( $param ) {
    return var_dump( $param );    

# Example 3: Assign an anonymous function to an variable

$say_hello = function ( $name ) {
    printf( "Hello %s!%s", $name, PHP_EOL );
$say_hello( 'PHP' );

# Example 4: An anonymous function inside a function of a class

class Test
    public function testing()
        return function() {
            var_dump($this); // It have access to $this

Arrow functions

Arrow functions were introduced in PHP 7.4. They are like anonymous functions, but more handy. A main difference is arrow functions use variables from the parent scope automatically however anonymous functions do not. In fact, both of them are implemented by using the Closure class.

Like other languages, array functions in PHP have the basic form:

fn ( args ) => expr;


# Example 1

$a = 1;
$fn = fn($x) => $x + $a;

echo $fn( 2 ); // Outputs 3

# Example 2: Values from the outer scope cannot be modified by arrow functions

$a = 1;
$fn = fn() => $x++; // Has no effect
echo $a;  // Outputs 1

# Example 3: Nested arrow function

$z = 1;
$fn = fn( $x ) => fn( $y ) => $x * $y + $z;

echo $fn( 5 )( 10 ); // Outputs 51

PHP Type

PHP supports ten primitive types (including a pseudo-type). Except object, the rest 9 types will be introduced in this article.

The full list of ten primitive types in PHP

  • boolean
  • integer
  • float (aka double)
  • string
  • array
  • NULL
  • callable (aka callback)
  • resource
  • iterable (a pseudo-type)
  • object (OOP concept, an instantiated class)



A value of boolean can be TRUE or FALSE. TRUE and FALSE are two predefined constants in PHP. They are case-insensitive

$foo = true; // OK
$foo = TRUE; // OK

Some operators’s result is a boolean value.

if ( $action === 'create' ) {
    // do something

if ( $is_weekday == true ) {
    // do something

if ( $is_weekday ){
    // do something

$a = 0;
if ( $a == 'apple' ) { // true, use === instead

Convert to boolean

# Convert to boolean
$a = (bool) 1; // true
// or
$a = (boolean) 1; // true

The following values are considered FALSE.

  • boolean FALSE
  • integer 0 and -0
  • float 0.0 and -0.0
  • empty string
  • empty array
  • NULL
  • object SimpleXML created from empty tags
$a = (bool) -1; // true

$b = (bool) array(); // false
$c = (bool) ''; // false



The size of an integer is platform-dependent. 64-bit platforms usually have a maximum value of about 9E18, except on Windows prior to PHP 7, where it was always 32 bit.

  • There are some predefined constant for integers.
    • PHP_INT_SIZE (integer). The size of an integer in byte.
    • PHP_INT_MAX (integer). The largest integer supported in this build of PHP. Usually int(2147483647) in 32 bit systems and int(9223372036854775807) in 64 bit systems.
    • PHP_INT_MIN (integer). The smallest integer supported in this build of PHP. Usually int(-2147483648) in 32 bit systems and int(-9223372036854775808) in 64 bit systems.
  • PHP does not support unsigned integers.
$a = 1234; // decimal number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
$a = 0b11111111; // binary number (equivalent to 255 decimal)

Convert to integer

# use (int) or (integer)
$i = ( int ) 1.0;
// or
$i = ( integer ) 1.0;

$a = ( int) false; // 0
$b = ( int ) null;// 0
$c = ( int ) '123'; // 123

# use
$f = intval( '123' ); // 123



The size of a float is platform-dependent. There are some predefined constant for floats.

  • PHP_INT_SIZE (integer). The size of an integer in bytes in this build of PHP.

  • PHP_FLOAT_DIG (integer). Number of decimal digits that can be rounded into a float and back without precision loss. Available as of PHP 7.2.0.

  • PHP_FLOAT_EPSILON (float). Smallest representable positive number x, so that x + 1.0 != 1.0. Available as of PHP 7.2.0.

  • PHP_FLOAT_MIN (float). Available as of PHP 7.2.0.

  • PHP_FLOAT_MAX (float). Available as of PHP 7.2.0.

$a = 95.8;
$b = 1.1e3;

Convert to float

# Convert string to float

$foo = 1 + "10.5";                // $foo is float (11.5)
$foo = 1 + "-1.3e3";              // $foo is float (-1299)
$foo = 1 + "bob-1.3e3";           // $foo is integer (1)
$foo = 1 + "bob3";                // $foo is integer (1)
$foo = 1 + "10 Small Pigs";       // $foo is integer (11)
$foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2)

# Convert other types to float, they will be converted to integer first then to float.

$foo = 1.1 + TRUE; // 2.1
$foo = 1.1 + FALSE; // 1.1

Compare floats

Do not compare two floats directly for equity.

# Compare $a and $b in 5 digits precision.

$a = 1.23456789;
$b = 1.23456780;
$epsilon = 0.00001;

if( abs( $a - $b ) < $epsilon ) {
    echo "true";


In floating-point calculations, the result may be an undefined value,then it is represented by the constant NAN (Not a Number).

NAN should not be compared to other values, for it can represents any number of values. Use is_nan() to check it. Note it is case sensitive.

// Check whether a caculation's result is NAN.
var_dump( is_nan( acos( 2 ) ) ); // bool(true)

var_dump( NAN ); // float(NAN)



A string is a series of characters.

  • PHP only supports a 256-character set, no native Unicode support.
  • As of PHP7.0.0, on 64-bit build, no particular restrictions to the length of a string. On 32-bit build in earlier versions, a string can be as large as up to 2GB (2147483647 bytes maximum).

A string literal can be specified in different ways, mainly single quoted and double quoted.

Single quoted

$a = 'abc';                  // abc

// Only ' and \ are treated as escaped characters in single quoted strings
$b = 'I'm a character.';    // I'am a character.
$c = 'c:\users\john';      // c:usersjohn

// Other  will be treated as  itself literally.
$d = 'First line rn Second linern'; // First line rn Second linern

Double quoted

In double quoted stings, escape sequences for special characters will be interpreted. Escaped characters include n, r, t, v, e, f, \, $, ", [0-7]{1,3}, x[0-9A-Fa-f]{1,2}], u{[0-9A-Fa-f]+}.

echo "5$";   // 5$

$a = "101";  // 'A' in ocatl notation.
echo $a;      // A

$b = "x41";  //  'A' in hexadecimal notation.
echo $b;      // A

$c = "u41";  // Unicode codepoint
echo $c;      // u41

Check a string’s value with var_dump()

Note if you dump information of a string with var_dump(), the escape characters will be interpreted as printed.

$a = 'I'm a character.';
var_dump( $a );
/* output
string(16) "I'm a character."

$b = "First line \rn Second line \rn";
var_dump( $b );
/* output
string(32) "First line .
 Second line .

Variable parsing

When a string is specified in double quotes , variables are parsed within it. If you want literal $ and {}, remember to escape them with $ ,{ or }.

// If a dollar sign ($) is encountered, the parser will greedily take
// as many tokens as possible to form a valid variable name.

$name = 'John';
$s = "I am $name."; // I am John.
$s = ""

// Enclose the variable name in {} to explicitly specify the end of the name.

$frute = 'apple';
$s = "I have many ${frute}s."; // I have many apples.

// {} can be used in some complex expressions

$arr = array(
    'frute' => array('Apple', 'Banada' ),
    'vegetable' => array( 'Tomato', 'Potato' )
$s = "frutes: {$arr['frute'][0]}, {$arr['frute'][1]}";

$s = "You are {${get_name()}}"; // return value of function get_name()

$name = 'month';
$$name = 'January'; // variable variable, $month = 'January'
$s = "It is {${$name}}."; // It is January.

Access and modify by character

$s = 'Hello world!';
$first = $s[0]; // H

$s[5] = ',';
echo $s; // Hello,world!

$s[strlen( $str ) - 1] = '.';
echo $s; // Hello,world.

Convert to string

Use (string or strval().

$a = (string) true;  // "1";
$b = (string) false; // ""
$c = (string) 123;   // "123"
$d = strval( 123 );  // "123"



An array in PHP is actually an ordered map. It can be used as a list, map, stack, queue, etc. If an array used as a map , each value is treated as an key-value pair. If the key is not specified, it will be its index. Therefor an array in PHP may be an normal indexed array or an associative array ( explicit key-value pairs as values), PHP does not distinguish between them.

  • The key is optional, if it is not specified, it will increase automatically.

  • The key may be an integer or a string, the value can be of any type.

  • An array’s keys can contain both integers and strings at the same time, if a key is not specified, it will increase based on the largest previously used integer key (if it exists), if no integer key is used previously, it will be 0.

    $mixed_array = array (
      'a' =&gt; 'Apple',
      'Fruit',            // The key will be 0
      100 =&gt; 'Tomato',
      1   =&gt; 'Vegetable',
      'Cherry'            // The key will be 100 + 1
    var_dump( $mixed_array );
    /* output
    array(5) {
    string(5) "Apple"
    string(5) "Fruit"
    string(6) "Tomato"
    string(9) "Vegetable"
    string(6) "Cherry"


Understanding an PHP array being actually a map is very important. For example, when you remove an element from an array using unset() , you will know that the element’s keys/index left in the array will not be be changed, just like you do such an operation on a map.


// Create an array

$a = array(1, 2, 3);
// or
$a = [1, 2, 3];

// Initiate an array with key-value pairs, then it is a associative array.
$b = array(
    'a' => 1,
    'b' => 2,
    'c' => 3;

// Multidimensional arrays

$c = array(
    'a' => array(1, 2, 3),
    'b' => array(4, 5, 6),
    'c' => array(7, 8, 9)

// Access with []

echo $a[0];   // 1
echo $b['a']; // 1

// Modify with []

$a[0] = 100;
$b['a'] = 'Apple';

// Append a value

$d = array();
$d[] = 'Dog';    // Add a value to an array
$d[] = 'Duck';
$d['f'] = 'Fox'; // Add a key-value pair

// Remove a value

unset( $d[0] ); // Dog is removed from $d,$d now becomes array(1=>'Duck', 'f'=>'Fox').
                // Note the remained elements's keys will not changed,
                // because it is actually a map.
var_dump( $d );
/* output
array(1) {
  string(4) "duck"

// Traverse

foreach ( $a as $e ) {
    echo $e;
foreach( $a as $k => $v ) { // $k will be index if it is not specified
    echo $k . ': ' . $v;
foreach( $b as $k => $v ) {
    echo $k . ': ' . $v;

Convert to array

// Converting a single value to array results in an array with a single element.

$a = (array) 1;      // array(1)
$b = (array) 'abc';  // array('abc')
$c = (array) null;   // array()

// Converting an object to array result in an array
// whose elements are the object's properties


The Type NULL only have one value NULL which is a predefined constant. The value NULL represents a variable with no value.

A variable is considered to be NULL:

  • it has been assigned the constant NULL.
  • it has not been set to any value yet.
  • it has been unset with function unset().
$a = null;
if ( is_null( $a ) ) {
    $a = 'hello';
echo $a; // hello

unset( $a );
if ( is_null( $a ) ) {
    $a = 'world';
echo $a; // world


The type callable accepts a function as its value.

Some functions like call_user_func() or usort() accept values of type callable.

function func1() {
    echo 'func1';
call_user_func( 'func1' );

$func2 = function () {
    echo 'func2';
call_user_func( $func2 );

// Functions of a calss

class MyClass {
    function myMethod() {
        echo 'Hello World!';

    static function myStaticMethod() {
        echo 'Hello World!';

// Static method
call_user_func( array( 'MyClass', 'myStaticMethod' ) );
// or
call_user_func( 'MyClass::myStaticMethod' );

// Non-static method
call_user_func( array( new MyClass(), 'myMethod' ) );


A variable of type resource holds a reference to an external resource, such as a handle to an opened file, a database connection, an image canvas area, etc. It is created and used by special functions.

Note: A resource with no more references will be freed by the garbage collector automatically.


Iterable is a pseudo-type in PHP. That means get_type()(Gets a variable’s type, see more on type judging) will not return the type iterable no matter it is an iterable or not.

It accepts any array or object implementing the Traversable interface.

// An iterable value as parameter,
function foo( iterable $arr = [] ) {
    foreach ( $arr as $v ) {
        // do something

PHP Constant

Compared to a variable, a constant’s value can not be changed during the execution of the script. Use define to define a constant. Generally, a constant’s name use uppercase representation.

  • A constant’s scope is global.
  • Reserved constant start with __. It’s better not to define constants with __ started.

Define constant

define('VERSION', '1.0');
define('MAX_VALUE', 100 );
define('PATH', __DIR__ ); // __FILE__ is a magic constant,it is the current file's directory.

Predefined constants

PHP provides a large number of predefined constants to any script which it runs.

  • TRUE (boolean)
  • FALSE (boolean)
  • NULL (null)
  • PHP_INT_SIZE (integer). The size of an integer in bytes in this build of PHP. Available since PHP 5.0.5
  • PHP_INT_MAX (integer). The largest integer supported in this build of PHP. Usually int(2147483647) in 32 bit systems and int(9223372036854775807) in 64 bit systems. Available since PHP 5.0.5
  • PHP_FLOAT_MAN (float)
  • PHP_FLOAT_MIN (float)
  • PHP_EOL (string). The correct ‘End Of Line’ symbol for this platform.
    Available since PHP 5.0.2
  • PHP_VERSION (string), the current PHP version
  • PHP_VERSION_ID (integer). The current PHP version as an integer, useful for version comparisons (e.g., int(50207) from version “5.2.7-extra”).
    Available since PHP 5.2.7.
  • PHP_OS (string). The operation system family PHP was built for.One of
    ‘Windows’, ‘BSD’,
    ‘Darwin’, ‘Solaris’,
    ‘Linux’ or ‘Unknown’.
    Available as of PHP 7.2.0.
  • E_ERROR (integer). Error reporting constant。
  • E_WARNING (integer)
  • E_NOTICE (integer)
  • E_ALL (integer)

See reserved constants for a full list of predefined constants.


// Check OS
if ( PHP_OS == 'Windows' ) {
    echo 'this is a windows system';

// Write 2 lines of content to a file
$content = 'The first line.' . PHP_EOL;
$content .= 'The second line.' . PHP_EOL . PHP_EOL;
file_put_contennts ( 'test.txt', $content );

Magic constants

There are nine magical constants that change depending on where they are used. Therefore they aren’t actually constants.

Unlike regular constants which are resolved at runtime, magic constants are resolved at compile time.

Note: Magic constants are case-insensitive.

Name Description
__LINE__ The current line number of the file.
__FILE__ The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.
__DIR__ The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.
__FUNCTION__ The function name, or {closure} for anonymous functions.
__CLASS__ The class name. The class name includes the namespace it was declared in (e.g. FooBar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.
__TRAIT__ The trait name. The trait name includes the namespace it was declared in (e.g. FooBar).
__METHOD__ The class method name.
__NAMESPACE__ The name of the current namespace.
ClassName::class The fully qualified class name. See also ::class.


define( 'PATH', __DIR__ );

require_once( 'PATH' . '/inc.php' );

PHP Variable

In PHP, a variable is represented by a dollar sign followed by the name.

  • A variable name is case sensitive.
  • A variable does not have a type declaration. Its type is determined by its value.


Assign by value

This is the general assignment, assign a value to a variable.

$name = 'John';
$foo = 12;

Assign by reference

In this way, a new variable just references (meaning “alias for”) an original variable. Changes to the new variable affect the original, vice versa.

$a = 'Apple';
$b = &$a;
echo $b; // Apple

# Change $b
$b = 'Banada';
echo $a; // Banada
echo $b; // Banada

# Change $a
$a = 'Cherry';
echo $a; // Cherry
echo $b; // Cherry

The variable referencing other variable can not be assigned by reference. Only named variables can be assigned by reference.

Default value

If a variable is not initialized, it have a default value of its type depending on the context in which it is used.

var_dump( $unset_var );
// output:
// PHP Notice:  Undefined variable: unset_var in php shell code on line 1
var_dump(  $unset_var );

$unset_str .= 'abc';
var_dump( $unset_str ); // output: string(3) "abc"

Note: It is a security risk to rely on the default value, especially it is included into another file which has the same variable name.

Good practice

Always initialize a variable, give it a default value.

Variable variable

A variable variable is the name can be set and used dynamically.

For example, use the value $a as the name of another variable. The latter one is a variable variable.

$a = 'month';
$$a = 'January';

echo $$a; // January
echo $month; // January

// Used in an array
// $$a[1] will be ambiguous:
// the variable variable name is $a[1] or $a and it is an array.
// Use {} to resolve the ambiguity.
${$a[1]}; // the variable variable name is $a[1]
${$a}[1]; // the variable variable name is $a

Variable variables can not be used with PHP’s Superglobals arrays (built-in global variables ) within functions or class methods.


A variable’s scope is the context within which it is defined. The scope includes included and required files.

However, different from other languages, to access variables from global scope within a function, you need declare them global. Because variables used within a function is by default limited to the function scope. For variables inside a block, they are still available outside the block.

$a = 1; // global scope

include 'inc.php'; // $a is available in inc.php

function test() {
    echo $a; // $a is not available
    global $a;
    echo $a; // $a is availabe now

for( $i = 0; $i < 10; $i++ ) {
    if ( $i === 0 ) {
        $started = true;

// 10
echo $i; // $i is still available outside the block
// true
echo $started; // $started is still available outside the block

Static variable scope

A static variable exists only in a local function scope, but it does not lose its value when leaving this scope.

function my_count() {
    static $n = 0;
    echo $n;

my_count(); // 1
my_count(); // 2


If a static variable is assigned by reference, it’s not remembered.

Predefined Variables

There are a large number of predefined variables to all scripts.


Several predefined variables are superglobals which are available in all scope. There is no need to declare them global within functions.