Curriculum
This tutorial will teach you about PHP type casting, which allows you to convert a value of one type to another.
Type casting is the process of converting a value of one type to another. To cast a value, use the type casting operators listed below:
The (int) type casting operator is used to convert a value to an integer.
The (int) operator is used to convert a float to an integer. It will round the result to zero. As an 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>'; // -12
Assume you have a string and want to convert it to an integer:
<?php $message = 'Hi'; $num = (int) $message; echo $num; // 0
The outcome might not be what you expected.
If a string contains numeric or leading numeric characters, the (int) function will convert it to the corresponding integer value. If not, the (int) casts the string to zero. As an example:
<?php $amount = (int)'100 USD'; echo $amount; // 100
The (int) operator in this example converts the string ‘100 USD’ to an integer.
It’s worth noting that the (int) operator converts null to zero (0). As an example:
<?php $qty = null; echo (int)$qty; // 0
The (float) operator is used to convert a value to a float. As an example:
<?php $amount = (float)100; echo $amount; // 100
The (string) operator is used to convert a value to a string.
The (string) operator is used in the following example to convert the number 100 to a string:
<?php $amount = 100; echo (string)$amount . " USD"; // 100 USD
In this case, you don’t need to use the (string) operator because PHP has a feature called type juggling that converts the integer to a string implicitly:
<?php $amount = 100; echo $amount . ' USD'; // 100 USD
True values are converted to the string “1,” while false values are converted to the empty string (“”). As an example:
<?php $is_user_logged_in = true; echo (string)$is_user_logged_in; // 1
(string) converts null to an empty string.
The (string) function converts an array to the string “Array.” As an example:
<?php $numbers = [1,2,3]; $str = (string) $numbers; echo $str; // Array
You will also receive a warning that you are attempting to convert an array to a string.
Warning: Array to string conversion in …