Skip to content

PHP Tutorial Data Types

Type Casting

Lesson 44 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Type casting means converting a value to another type on purpose. You write the target type in brackets in front of the value.

CastResult
(int)integer
(float)float
(string)string
(bool)boolean
(array)array
(object)object

To integer

index.php
PHP
<?php
var_dump((int) "42");
var_dump((int) 9.99);
var_dump((int) "12 apples");
var_dump((int) "apples");
var_dump((int) true);
Output
OUTPUT
int(42)
int(9)
int(12)
int(0)
int(1)

Two things to notice. Casting a float to an int cuts off the decimals (it does not round). And text that does not start with a number becomes 0.

To float and string

index.php
PHP
<?php
var_dump((float) "3.5");
var_dump((string) 25);
var_dump((string) true);
var_dump((string) false);
Output
OUTPUT
float(3.5)
string(2) "25"
string(1) "1"
string(0) ""

To boolean

index.php
PHP
<?php
var_dump((bool) 0);
var_dump((bool) 1);
var_dump((bool) "");
var_dump((bool) "0.0");
Output
OUTPUT
bool(false)
bool(true)
bool(false)
bool(true)

To array

Casting a single value to an array wraps it in a list.

index.php
PHP
<?php
print_r((array) "hello");
Output
OUTPUT
Array
(
    [0] => hello
)

Cast functions

intval(), floatval() and strval() do the same as the casts and are handy as callbacks.

index.php
PHP
<?php
print_r(array_map("intval", ["1", "2", "3"]));
Output
OUTPUT
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
warning
A cast does not validate
(int) "abc" quietly gives 0, which could be mistaken for real input. For user data, validate first (for example with filter_var($v, FILTER_VALIDATE_INT)), then cast.