Home > Backend Development > PHP Problem > How to change the type in php

How to change the type in php

藏色散人
Release: 2023-03-17 13:20:01
Original
2034 people have browsed it

php method to change type: 1. Convert to integer through (int) or (integer); 2. Convert to floating point type through (float), (double) or (real); 3. Convert to floating point type through ( string) into a string; 4. Convert into a Boolean type through (bool) or (boolean); 5. Convert into an array through (array); 6. Convert into an object through (object).

How to change the type in php

The operating environment of this tutorial: Windows 7 system, PHP version 8.1, Dell G3 computer.

php How to change the type?

PHP data type conversion

PHP data type conversion is a forced conversion. The PHP data types that are allowed to be converted are:

(int)、(integer):转换成整形
(float)、(double)、(real):转换成浮点型
(string):转换成字符串
(bool)、(boolean):转换成布尔类型
(array):转换成数组
(object):转换成对象
Copy after login

There are three conversion methods for PHP data types:

Add the target type enclosed in parentheses before the variable to be converted

Use 3 specific Type conversion functions, intval(), floatval(), strval()

Use the general type conversion function settype(mixed var, string type)

The first conversion method:

(int) (bool) (float) (string) (array) (object)

<?php   
$num1=3.14;   
$num2=(int)$num1;   
var_dump($num1); //输出float(3.14)   
var_dump($num2); //输出int(3)   
?>
Copy after login

The second conversion Method:

intval() floatval() strval()

<?php   
$str="123.9abc";   
$int=intval($str);     //转换后数值:123   
$float=floatval($str); //转换后数值:123.9   
$str=strval($float);   //转换后字符串:"123.9"    
?>
Copy after login

The third conversion method:

settype();

<?php   
$num4=12.8;   
$flg=settype($num4,"int");   
var_dump($flg);  //输出bool(true)   
var_dump($num4); //输出int(12)   
?>
Copy after login

Supplement:

Judge string All composed of numbers

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

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to change the type in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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