Home  >  Article  >  Backend Development  >  Detailed explanation of three methods of PHP data type conversion

Detailed explanation of three methods of PHP data type conversion

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-03-24 17:56:576492browse

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.

Detailed explanation of three methods of PHP data type conversion

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),&#39;--&#39;,gettype(500),&#39;<hr>&#39;;
    echo gettype(strval(500)),&#39;--&#39;,gettype(500),&#39;<hr>&#39;;
    echo gettype(strval(true)),&#39;--&#39;,gettype(true),&#39;<hr>&#39;;
?>

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),&#39;<hr>&#39;;
    $current=gettype(settype($old,&#39;string&#39;));
    echo "现类型". gettype($current),&#39;<hr>&#39;;
?>

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),&#39;--&#39;,gettype($str),&#39;<hr>&#39;;
    echo floatval($str),&#39;--&#39;,gettype($str),&#39;<hr>&#39;; 
    echo strval($str),&#39;--&#39;,gettype($str),&#39;<hr>&#39;;  
?>

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn