How to Convert Data Types in PHP

09/07/2021

Contents

In this article, you will learn how to convert data types in PHP.

Convert Data Types

In PHP, data types can be converted using type casting or type juggling.

Type casting involves explicitly converting a value to a specific data type, using the following syntax:

(data_type) $value;

Type casting is useful when you need to ensure that a value has a specific data type, regardless of its original type. The most commonly used type casts in PHP are (int), (float), (string), (array), and (object).

For example:

<?php
  $float = 3.14;
  $int = (int) $float;

  $array = [1, 2, 3];
  $string = (string) $array;
?>

In the first example, the float value 3.14 is cast to an integer, resulting in the value 3. In the second example, casting an array to a string results in the string Array.

Type juggling, on the other hand, is a process where PHP automatically converts data types based on the context in which they are used.

For example:

<?php
  $string = "123";
  $int = $string + 0;
?>

In this example, the string “123” is automatically cast to an integer 123, and the result of the expression is 123.