[PHP] Data type conversion, judgment, acquisition and setting

1. Two types of conversion methods

1. Automatic conversion: the system automatically determines the conversion according to the demand (commonly used, low efficiency)

2. Mandatory (manual) conversion: artificial conversion according to needs.
Mandatory conversion rule: add a bracket () before the variable, and then write the corresponding type in it, such as

echo (float)$a;

Note: 1. Commonly used is
to convert Boolean type (used for judgment) and numeric type (used for calculation) 2. Coercion is a copy of a copy for conversion, which is similar to value transfer and does not change the original variable, such as:

$a = 'abc123';
(float)$a;
echo $a;
//其结果仍然是abc123
echo (float)$a;
//这样结果才能是0,但再次调用a变量时,依然是原来的

Description of other types of transfer values

String conversion has its own rules:

  • A string beginning with a letter is always 0, for example:
$a = 'abc1.2';//转换为0
$b = '2.1';//转换为浮点类型的2.1
echo $a + $b;
//结果是2.1
  • The string starting with a number is taken until it reaches the string (not including two decimal points at the same time), for example:
$c = '1.1.1abc';
$d = '7';
echo $c + $d;
//结果是8.1

Second, the judgment of data type

The variable is judged through a set of type judgment functions, and finally the data type of the data stored in the variable is returned (the same result is true, and the failure is false).

The format is: is_ type name (variable name)

Note: The bool type cannot be viewed by echo, it can be viewed by the var_dump structure

var_dump(variable 1, variable 2...)

    $a = 'abc1.1.1';
    var_dump(is_int($a));
    //结果为bool(false),因为a是字符串
    var_dump(is_string($a));
    //结果为bool(true)

	来个容易理解的:
	var_dump(is_pig($you));//hhhhh

Three, get and set the data (variable) type-gettype and settype

1. Gettype gets the type of variable:

    $b = '1.1.1abc';  
    echo gettype($b);
    //结果为string

2, settype sets the variable type

$a = '1.1.1abc';
settype($a,'int');
echo gettype($a);//来看一下$a现在是什么类型
echo $a;
//结果一个是integer,一个是1

At the same time, settype itself returns a bool value, so var_dump can be used to determine whether the setting is successful:

$a = '1.1.1abc';
var_dump(settype($a,'int'));
//结果应该返回bool(true),即设置成功

Finally, attach some function tables that return bool typeInsert picture description here

Guess you like

Origin blog.csdn.net/qq_44899247/article/details/105275489