Home > Article > Backend Development > Detailed explanation of three methods of PHP data type conversion
There are three conversion types for data, namely forced conversion, permanent conversion, and conversion function conversion. This article introduces these three conversion methods to give you an in-depth understanding of type conversion. Let's learn with the editor together.
The first type, forced conversion
The data passed through forced conversion does not affect the original type of the data, but only changes the data Temporarily converted.
<?php echo gettype((string)500),'--',gettype(500),'<hr>'; echo gettype(strval(500)),'--',gettype(500),'<hr>'; echo gettype(strval(true)),'--',gettype(true),'<hr>'; ?>
The result is:
string--integer string--integer string--boolean
You can see that although we have converted the data type, what type was the original data and what type is it still? , the original type is not changed due to type conversion.
Second type, permanent conversion
<?php $old=500; echo "原类型".gettype($old),'<hr>'; $current=gettype(settype($old,'string')); echo "现类型". gettype($current),'<hr>'; ?>
The result is:
原类型integer 现类型string
By permanently converted data, The original type of its data has also changed.
echo gettype($old);
The result is:
string
Through the above case, we can see that after we convert the data, our original data type also changes.
The third type, conversion function conversion
Convert through the three conversion functions intval() floatval() strval(), which can be converted into different types according to needs.
<?php $str="123.9abc"; echo intval($str),'--',gettype($str),'<hr>'; echo floatval($str),'--',gettype($str),'<hr>'; echo strval($str),'--',gettype($str),'<hr>'; ?>
Let us take a look at his output:
123--string 123.9--string 123.9abc--string
You can see different conversion functions, converted into different types, and the original The string type does not change.
Recommended: "PHP Video Tutorial"
The above is the detailed content of Detailed explanation of three methods of PHP data type conversion. For more information, please follow other related articles on the PHP Chinese website!