In PHP, **casting** refers to the process of converting a value from one data type to another. This can be done either explicitly (manually) or implicitly (automatically). Understanding casting helps in ensuring that data is properly handled and manipulated within different data types.
In implicit casting, PHP automatically converts the data type when performing operations. For example, when an integer is added to a float, PHP automatically converts the integer to a float.
<?php $intVar = 10; // Integer $floatVar = 10.5; // Float $result = $intVar + $floatVar; // Integer is automatically cast to float echo $result; // 20.5 ?>
Explicit casting is when you manually convert a value to another data type. You can use the casting operator `(type)` to do so.
(int)
or (integer)
(float)
, (double)
, or (real)
(string)
or (str)
(bool)
or (boolean)
<?php $strVar = "100.5"; // String $intVar = (int)$strVar; // Explicitly cast string to integer echo $intVar; // 100 $intVar2 = 10; $floatVar2 = (float)$intVar2; // Explicitly cast integer to float echo $floatVar2; // 10.0 ?>
(int)
(float)
(bool)
(string)
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!