Home >Backend Development >PHP Problem >How to convert numbers into strings in php?

How to convert numbers into strings in php?

青灯夜游
青灯夜游Original
2020-11-05 15:38:533934browse

How to convert numbers into strings in php: 1. Use forced type conversion, syntax "(string)number"; 2. Use strval() function, syntax "strval(number)"; 3. Use the settype() function, the syntax is "settype(number, "string")".

How to convert numbers into strings in php?

Recommended: "PHP Video Tutorial"

php Convert numbers into strings Method

1. Forced type conversion

Type coercion in PHP is very similar to that in C: add before the variable to be converted The target type enclosed in parentheses.

The allowed casts are:

  • (int),(integer) - Convert to integer type

  • (bool ),(boolean) - Convert to Boolean type

  • (float),(double),(real) - Convert to floating point type

  • (string)                                                                                                                                                                                                                                         through

  • Note that spaces and tabs are allowed within brackets

  • Example:

    <?php   
    $num1=314;   
    $num2=(string)$num1;   
    var_dump($num1); 
    var_dump($num2); 
    ?>

    Output:
int 314
string &#39;314&#39; (length=3)

2. Use the strval() function

The strval() function is used to obtain the string value of the variable.

Example:

<?php   
$num=31415;   
$str=strval($num); 
var_dump($num);  
var_dump($str); 
?>

Output;

int 31415
string &#39;31415&#39; (length=5)

3. Use the settype() function


settype () function is used to set the type of variables.

settype ( var , type )


Return value: TRUE when the setting is successful, FALSE when the setting fails. Example:

<?php   
$num=12.8;   
$str=settype($num,"string");   
var_dump($str);  
var_dump($num); 
?>

Output:

boolean true
string &#39;12.8&#39; (length=4)
How to convert numbers into strings in php?

Supplement:

Judgment string is all composed of numbers

<?php
$str = "123"
if(ereg(&#39;^[0-9]+$&#39;, $str)) {
    // true
}
?>

For more programming-related knowledge, please visit:

Introduction to Programming

! !

The above is the detailed content of How to convert numbers into strings 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