Current Location: Home> Latest Articles> In-Depth Guide to Type Casting in PHP8 with Practical Examples

In-Depth Guide to Type Casting in PHP8 with Practical Examples

M66 2025-07-21

Introduction

In PHP8, data type conversion is a fundamental aspect of programming that allows developers to convert one data type into another. This functionality provides greater flexibility when processing data. This guide walks you through how type casting works in PHP8 and includes practical code examples to illustrate its usage.

Explicit Type Casting

PHP8 provides various ways to perform explicit type conversions when you need to manually change the type of a variable.

Integer Casting

Use (int) or (integer) to convert a variable to an integer.

$a = 3.14;
$b = (int)$a;
echo $b; // Outputs 3

Float Casting

Use (float) or (double) to convert a variable to a floating-point number.

$a = 3;
$b = (float)$a;
echo $b; // Outputs 3.0

String Casting

Use (string) to convert a variable into a string.

$a = 123;
$b = (string)$a;
echo $b; // Outputs "123"

Boolean Casting

Use (bool) or (boolean) to convert a variable to a boolean value.

$a = "";
$b = (bool)$a;
echo $b; // Outputs false

Array Casting

Use (array) to convert a variable into an array.

$a = "Hello";
$b = (array)$a;
print_r($b); // Outputs Array ( [0] => Hello )

Object Casting

Use (object) to convert a variable into an object.

$a = "Hello";
$b = (object)$a;
echo $b->scalar; // Outputs Hello

Automatic Type Conversion

Besides explicit conversions, PHP8 also performs automatic type juggling based on the context of the operation.

Integer and Float Auto Conversion

When an integer and a float are involved in an operation, PHP automatically converts the integer to a float and returns a float result.

$a = 5;
$b = 2.5;
$c = $a + $b;
echo $c; // Outputs 7.5

String and Number Auto Conversion

When a string is involved in a numerical operation, PHP converts the string to a number.

$a = "10";
$b = 5;
$c = $a + $b;
echo $c; // Outputs 15

String and Boolean Auto Conversion

When a string and a boolean are used in an operation, PHP converts the string to a boolean.

$a = "true";
$b = false;
$c = $a && $b;
var_dump($c); // Outputs bool(false)

Array and String Auto Conversion

When an array is concatenated with a string, PHP converts the array to the string "Array".

$a = array(1, 2, 3);
$b = "Hello";
$c = $a . $b;
echo $c; // Outputs "ArrayHello"

Conclusion

Type conversion in PHP8 plays a crucial role in handling data dynamically. This guide covered both explicit and automatic conversions, supplemented with clear examples. Understanding and utilizing these features will help you write more efficient and robust PHP code.