How to convert numbers into strings in php?

青灯夜游
Release: 2023-03-07 11:38:02
Original
3905 people have browsed it

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); 
    ?>
    Copy after login

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

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); 
?>
Copy after login

Output;

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

3. Use the settype() function


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

settype ( var , type )
Copy after login


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); 
?>
Copy after login

Output:

boolean true
string &#39;12.8&#39; (length=4)
Copy after login
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
}
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template