Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Data types

Every value in PHP has a type: a number, a string, a boolean and so on. The type is determined automatically from the value itself, and one variable may hold values of different types at different times.

Main types

TypeExampleDescription
string'text'A string
int42An integer
float3.14A floating-point number
booltrueTrue or false
array[1, 2, 3]A collection of values
nullnullNo value

Checking the type

The var_dump() function prints the type and the value. It is invaluable for debugging, when you need to see what a variable really holds:

<?php
 
var_dump('text'); // string(4) "text"
var_dump(42);     // int(42)
var_dump(3.14);   // float(3.14)
var_dump(true);   // bool(true)

The number in parentheses next to a string is its length in bytes. In UTF-8 a non-ASCII character such as a Cyrillic letter takes two bytes, so the reported length can be larger than the number of characters.

Integers and floats

Division always gives a float when the numbers do not divide evenly. Use intdiv() for integer division:

<?php
 
var_dump(10 / 4);        // float(2.5)
var_dump(intdiv(10, 4)); // int(2)

Floats are stored approximately, so they must not be compared for exact equality:

<?php
 
var_dump(0.1 + 0.2 == 0.3); // bool(false)

This is true of almost every programming language; it is not a PHP bug.

Type casting

You can change a type explicitly by putting the target type in parentheses before the value:

<?php
 
var_dump((int) '42');    // int(42)
var_dump((int) '12abc'); // int(12)
var_dump((string) 3.14); // string(4) "3.14"
var_dump((bool) '');     // bool(false)

When converting to bool, the values 0, 0.0, an empty string, the string '0', an empty array and null are false. Everything else is true.

Strict and loose comparison

The == operator converts both values to a common type before comparing, while === compares both the value and the type:

<?php
 
var_dump('5' == 5);  // bool(true)
var_dump('5' === 5); // bool(false)

Loose comparison often produces surprising results, so use === by default.

Thanks for reading!

Donate to the site — we work hard for you.