Home  >  Article  >  Backend Development  >  How to force convert data to string type in php

How to force convert data to string type in php

青灯夜游
青灯夜游Original
2022-09-23 18:17:513256browse

Two conversion methods: 1. Add the target type "(string)" enclosed in parentheses before the data, and the syntax "(string) specifies data". 2. Use the forced type conversion function strval() or settype(), with the syntax "strval(specified data)" or "settype(specified data 2, "string")".

How to force convert data to string type in php

The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer

php will strengthen the data Convert to string type

#Method 1: Add the target type "(string)" enclosed in parentheses before the data

  • (string): Convert to string

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$n=123;
var_dump($n);
var_dump((string)$n);
echo "<hr>";

$n=true;
var_dump($n);
var_dump((string)$n);
echo "<hr>";

$n=null;
var_dump($n);
var_dump((string)$n);
echo "<hr>";
?>

How to force convert data to string type in php

##Method 2: Use cast type conversion function

  • strval(): used to get the string value of a variable.

  • settype(): used to set a variable to a specified type (the settype() function will change the original type of the variable).

  • <?php
    header("Content-type:text/html;charset=utf-8"); 
    $n1 = 146;
    var_dump($n1);
    $str = strval($n1);
    echo &#39;变量 $n1 的类型为:&#39;.gettype($str).&#39;<br>&#39;;
    echo "<hr>";
    $n2= FALSE;
    var_dump($n2);
    $str = settype($n2,"string");
    echo &#39;变量 $n2 的类型为:&#39;.gettype($n2);
    ?>

How to force convert data to string type in php

Note: The value of the second parameter (set type) of the settype() function can be:

  • "boolean" (or "bool" since PHP 4.2.0)

  • "integer" (or "int" since PHP 4.2.0 onwards)

  • ##"float" (only available after PHP 4.2.0, "double" used in older versions is now disabled)
  • "string"
  • "array"
  • ##"object"
  • "null" (from PHP 4.2.0)
  • The settype() function will affect the type of the original variable.
Recommended learning: "

PHP Video Tutorial

"

The above is the detailed content of How to force convert data to string type in php. 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