PHP Type Casting

Summary: in this tutorial, you’ll learn about the PHP type casting that allows you to convert a value of a type to another.

Introduction to the PHP type casting

Type casting allows you to convert a value of one type to another. To cast a value, you use the following type casting operators:

Cast OperatorsConversion
(array)Array
(bool) or (boolean)Boolean
(int) or (integer)Integer
(object)Object
(real), (double), or (float)Float
(string)String

Let’s take some examples of using the type casting operators.

Cast to an integer

To cast a value to an integer, you use the (int) type casting operator.

The (int) operator casts a float to an integer. It’ll round the result towards zero. For example:

<?php

echo (int)12.5 . '<br>'; // 12
echo (int)12.1 . '<br>'; // 12
echo (int)12.9 . '<br>'; // 12
echo (int)-12.9 . '<br>'; // -12Code language: PHP (php)

Suppose you have a string and want to cast it as an integer:

<?php 

$message = 'Hi';
$num = (int) $message;
echo $num; // 0Code language: PHP (php)

The result may not be what you expected.

If a string is numeric or leading numeric, then the (int) will cast it to the corresponding integer value. Otherwise, the (int) cast the string to zero. For example:

<?php

$amount =  (int)'100 USD';
echo $amount; // 100Code language: PHP (php)

In this example, the (int) operator casts the string '100 USD' as an integer.

Note that the (int) operator casts null to zero (0). For example:

<?php

$qty = null;
echo (int)$qty; // 0Code language: PHP (php)

Cast to a float

To cast a value to a float, you use the (float) operator. For example:

<?php

$amount = (float)100;
echo $amount; // 100Code language: PHP (php)

Cast to a string

To cast a value to a string, you use the (string) operator.

The following example uses the (string) operator to cast the number 100 to a string:

<?php

$amount = 100;
echo (string)$amount . " USD"; // 100 USDCode language: PHP (php)

You don’t need to use the (string) operator in this case because PHP has a feature called type juggling that implicitly converts the integer to a string:

<?php

$amount = 100;
echo $amount . ' USD'; // 100 USDCode language: PHP (php)

The (string) operator converts the true value to the string "1" and false value to the empty string (“”). For example:

<?php

$is_user_logged_in = true;
echo (string)$is_user_logged_in; // 1Code language: PHP (php)

Output:

1Code language: PHP (php)

The (string) operator casts null to an empty string.

The (string) cast an array to the "Array" string. For example:

<?php

$numbers = [1,2,3];
$str = (string) $numbers;

echo $str; // ArrayCode language: PHP (php)

And you’ll get a warning that you’re attempting to convert an array to a string.

Warning: Array to string conversion in ...Code language: PHP (php)

Summary

  • PHP type casting allows you to convert a value from one type to another.
  • Use a type casting operator to cast a value to the desired type.
Did you find this tutorial useful?