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)

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. 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) {
    ["a"]=&gt;
    string(5) "Apple"
    [0]=&gt;
    string(5) "Fruit"
    [100]=&gt;
    string(6) "Tomato"
    [1]=&gt;
    string(9) "Vegetable"
    [101]=&gt;
    string(6) "Cherry"
    }
    */
    

Note:

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.

Examples

// 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) {
  [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

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()(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
    } 
}