Lesson 3 of 12

PHP Data Types

Every value in PHP has a type: is it text, a whole number, a decimal, yes/no, or a list? The type decides what you can do with the value. Adding two numbers makes sense; adding two dates written as text does not. In the previous lesson you learnt that PHP works types out for you. This lesson shows what those types are and how to keep them under control.

The main PHP data types

TypeExampleUsed for
string"Puducherry"Text of any length.
int42, -7Whole numbers.
float99.5, 1.2e3Numbers with a decimal part (also called double).
booltrue, falseYes/no answers, such as “is the user logged in?”
array["tea", "coffee"]An ordered list or a set of key/value pairs.
nullnullThe absence of a value.
objectnew DateTime()A bundle of data and behaviour built from a class.

Among the PHP data types, strings, integers, floats and booleans are called scalar types because they hold a single value. Arrays and objects can hold many values. You will study strings and arrays in their own lessons.

Inspecting a value with var_dump()

echo is fine for showing a value to a visitor, but it hides the type. For debugging, use var_dump(). It prints the type, the value and, for strings, the length in bytes. Get into the habit of using it whenever a result surprises you.

<?php
$name     = "Meena";
$age      = 28;
$height   = 5.4;
$isMember = true;
$skills   = ["Figma", "PHP"];
$nickname = null;

var_dump($name);
var_dump($age);
var_dump($height);
var_dump($isMember);
var_dump($skills);
var_dump($nickname);
Output
string(5) "Meena"
int(28)
float(5.4)
bool(true)
array(2) {
  [0]=>
  string(5) "Figma"
  [1]=>
  string(3) "PHP"
}
NULL

If you only need the type name as text, get_debug_type() returns it, for example "int" or "string". There are also checking functions such as is_int(), is_string(), is_array() and is_null(), which return true or false.

Booleans and “truthy” values

When PHP needs a yes/no answer, for example in an if statement, it converts other values to bool. These values count as false: 0, 0.0, "" (empty string), "0", an empty array and null. Everything else counts as true.

Watch out: The string "0" is treated as false, but "0.0" and " " (a space) are true. Surprises like this are why the operators lesson recommends strict comparison with ===.

null: no value yet

null is a type with only one value, also written null. It means “nothing here”, which is different from 0 or an empty string. A customer with no middle name, a search with no result or an optional setting that was never filled in are all good uses of null. Many PHP functions return null (or false) when they cannot find what you asked for, so always check the result before using it. Later you will meet ?? and ?->, two operators designed for working safely with values that might be null.

Floats are not exact

Computers store decimals in binary, so some values cannot be stored exactly. 0.1 + 0.2 is very slightly more than 0.3. For prices, a common approach is to store amounts in the smallest unit as integers, for example 49950 paise instead of 499.50 rupees, and format them only when printing.

Type juggling and casting

PHP automatically converts values when an operation needs a different type. This is called type juggling. "10" + 5 gives the integer 15, because + needs numbers. Juggling is convenient, but a string that is not numeric, such as "ten", causes a TypeError in PHP 8 when you try to add it.

You can also convert deliberately with a cast: write the target type in brackets before the value.

<?php
$quantityFromForm = "3";        // form data always arrives as a string
$quantity = (int) $quantityFromForm;

var_dump($quantity);
var_dump((float) "249.75");
var_dump((string) 2026);
var_dump((bool) "0");
var_dump((bool) "no");
var_dump(0.1 + 0.2 === 0.3);
echo get_debug_type($quantity);
Output
int(3)
float(249.75)
string(4) "2026"
bool(false)
bool(true)
bool(false)
int

Notice that (bool) "no" is true: any non-empty string other than "0" is truthy. Casting does not check meaning, it only follows the conversion rules.

Strict types

By default, if a function expects an int and you pass the string "5", PHP quietly converts it. Adding declare(strict_types=1); as the very first statement of a file switches this off for function calls made in that file: passing the wrong type then throws a TypeError instead of guessing. Most modern projects use strict types because bugs show up early instead of producing odd results later.

<?php
declare(strict_types=1);

function double(int $number): int
{
    return $number * 2;
}

echo double(21), "\n";

try {
    echo double("21");
} catch (TypeError $e) {
    echo "TypeError: a string is not an int";
}
Output
42
TypeError: a string is not an int

Do not worry about the function syntax yet; it is explained fully in PHP Functions. The try/catch part simply lets the script handle the error and carry on.

Tip: strict_types affects only the file it is written in, and only scalar type declarations on function calls. It does not stop "10" + 5 from working.

Further reading

Key takeaways

  • PHP has scalar types (string, int, float, bool) plus array, object and null.
  • Use var_dump() or get_debug_type() to see a value's real type while debugging.
  • 0, "", "0", [] and null are falsy; most other values are truthy.
  • Floats are approximate; avoid comparing them with === or using them for money.
  • Cast with (int), (float), (string) or (bool); add declare(strict_types=1); to catch type mistakes early.

Quick quiz

Check what you learned – pick an answer.

1. What does var_dump("42"); print?

2. Which value is treated as false in an if statement?

3. What does declare(strict_types=1); change?

Practice exercise

Store the form value "1499" (a string) in a variable, cast it to an integer, add 18% GST to get a float total, and use var_dump() to show the type and value of the original string, the integer and the total.

Show a hint

Multiply the integer by 1.18. The result of multiplying an int by a float is a float.

Show the solution
<?php
$priceText = "1499";
$price = (int) $priceText;
$total = $price * 1.18;

var_dump($priceText); // string(4) "1499"
var_dump($price);     // int(1499)
var_dump($total);     // float(1768.82)

Progress is saved in this browser only.