PHP Type

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

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)

Boolean

Basic

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

Integer

Basic

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

Float

Basic

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";
}

NAN

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)

String

Basic

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

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"

Array

Basic

An array in PHP is actually an ordered map. It can be used as a list, map, stack, queue, etc.

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

// key-value
$b = array(
    'a' => 1,
    'b' => 2,
    'c' => 3;
);
echo $b['a'];

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

// Traverse
foreach ( $a as $e ) {
    echo $e;
}
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/

NULL

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

Callable

The type callable accepts a function as its value.

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

function fun1() {
    echo 'fun1';
}
call_user_func( 'fun1' );

$fun2 = function () {
    echo 'fun2';
}
call_user_func( $fun2 );

// 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' ) );

Resource

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

Iterable is a pseudo-type in PHP. That means get_type() will not return a type iterable no matter it is a 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.

Examples

// 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.

Examples

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

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.

Scope

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;
    $n++;
    echo $n;
}

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

Note:

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.

Superglobals

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