PHP Casting

PHP Casting

Sometimes you need to change a variable from one data type into another. This process is called type casting.

Since PHP is loosely typed, it changes data types behind the scenes. But you can force a variable to be converted into a specific type.


Cast to Integer

You can cast a float or a string into an integer using (int) or (integer).

Example

<?php
// Cast float to int
$x = 23465.768;
$int_cast = (int)$x;
echo $int_cast; // Outputs 23465

// Cast string to int $y = "23465.768"; $int_cast_str = (int)$y; echo "\n" . $int_cast_str; // Outputs 23465 ?>

Other Casts