PHP data type conversion (character to number, number to character)

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

  • (int), (integer): Convert to integer
  • (float), (double), (real): Convert to float
  • (string): convert to string
  • (bool), (boolean): Convert to boolean type
  • (array): Convert to an array
  • (object): Convert to object

There are three conversion methods for PHP data types:

  • Prefix the variable to be converted with the target type enclosed in parentheses
  • Use 3 specific types of conversion functions, intval(), floatval(), strval() [Memory: the type of destination you want to convert + val()]
  • Use the generic type conversion function settype(mixed var,string type)

 The first conversion method: (int) (bool) (float) (string) (array) (object)

 
  1. <?php   
  2. $num1=3.14;   
  3. $num2=(int)$num1;   
  4. var_dump( $num1); //output float(3.14)   
  5. var_dump( $num2); //output int(3)   
  6. ?>  

The second conversion method: intval() floatval() strval()

 
  1. <?php   
  2. $str="123.9abc";   
  3. $int=intval($str); //The converted value: 123   
  4. $float=floatval($str); //The converted value: 123.9   
  5. $str=strval($float); // converted string: "123.9"    
  6. ?>  

The third conversion method: settype();

 
  1. <?php   
  2. $num4=12.8;   
  3. $flg=settype($num4,"int");   
  4. var_dump( $flg); //output bool(true)   
  5. var_dump( $num4); //output int(12)   
  6. ?> 

Reprinted from: http://www.tianzhigang.com/article.asp?id=280

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325814689&siteId=291194637