PHP type conversion && type casting

Source: Internet
Author: User
Tags comparison table integer numbers scalar type casting type null

Get data type:

If you want to see the value and type of an expression, use var_dump ().
If you just want an easy-to-read type of expression for debugging, use GetType ().
To view a type, do not use GetType () and use the Is_type () function.

Convert string to Numeric
    1. When a string is evaluated as a number, the type and value of the result are determined according to the following rules.
    2. If any one of the characters is included in ".", "E" or "E", the string is evaluated as a float. Otherwise, it is treated as an integer.
    3. The value is determined by the first part of the string. If the string starts with a valid numeric data, the number is used as its value, otherwise its value is 0 (0). Valid numeric data starts with an optional sign, followed by one or more digits (optionally including a decimal fraction) followed by an optional exponent. An exponent is an "E" or "E" followed by one or more numbers.
do not expect to be able to encode a character when converting it to an integer (which may also be done in C). If you want to convert between character encodings and characters, use the Ord () and Chr () functions.


Coercion Type casting (reference: PHP manual)

The type casts in PHP are very similar to those in C: precede the variables to be converted with the target type enclosed in parentheses.

The allowable casts are:

    • (int), (integer)-Converted to integral type
    • (bool), (Boolean)-converted to Boolean
    • (float), (double), (real)-converts to floating-point type
    • (string)-converts to a string
    • (array)-Convert an array
    • (object)-Convert to Object

Note that spaces and tabs are allowed inside the parentheses
You can also use Settype (mixed var,string type) to cast.

1. Cast to a Boolean value (BOOL) | (Boolean)

To explicitly convert a value to a Boolean, use either (BOOL) or (Boolean) to cast. However, in many cases it is not necessary to cast, because when an operator, function, or process control requires a Boolean parameter, the value is automatically converted.

When converted to Boolean, the following values are considered FALSE:

Boolean value FALSE
Integer value 0 (0)
Floating-point value 0.0 (0)
Blank string and string "0"
An array with no member variables
object with no cell (PHP 4 only)
Special type NULL (including variables that have not been set)
All other values are considered TRUE (including any resources)

?PHPVar_dump((BOOL) "");//bool (FALSE)Var_dump((bool) 1);//bool (TRUE)Var_dump((BOOL)-2);//bool (TRUE)Var_dump((bool) "foo");//bool (TRUE)Var_dump((bool) 2.3e5);//bool (TRUE)Var_dump((BOOL)Array(12));//bool (TRUE)Var_dump((BOOL)Array());//bool (FALSE)Var_dump((BOOL) "false");//bool (TRUE)?>

2. Cast to reshape (int) | (integer)
To explicitly convert a value to an integer, cast with (int) or (integer). However, in most cases there is no need to cast, because when an operator, function, or process control requires an integer parameter, the value is automatically converted. You can also convert a value to an integral type by using the function intval ().

A. Converting from BOOL
B. Converting from floating-point numbers

Rounding out, out of range, with uncertain results
C. Converting from a string to a numeric value
D. Convert from another type to a bool value, then convert

Never cast an unknown fraction to an integer, which can sometimes result in unexpected results.
<?php
echo (int) ((0.1+0.7) * 10); Showing 7
?>

$str = "123.456ABC7"; (int) 123
echo (int) $str;
$str = "abc123.456"; (int) 0
$str =true; (int) 1
$str =false; (int) 0


3. Cast to floating-point (int) | (double) | (real) |doubleval_r () |floatval () |intval ()
Accuracy: 0.12345678901234//Double,real all the same
Data loss parameter string converted to numeric value


4. Force swap to String (string) |strval ()

You can use the (string) tag or the Strval () function to convert a value to a string. When a string is required for an expression, the conversion of the string is done automatically within the scope of the expression. For example, when you use the Echo () or print () function, or when you compare a variable value to a string.
    • A Boolean value of TRUE will be converted to the string "1", and the value FALSE will be represented as "" (that is, an empty string). This allows you to randomly compare a Boolean value to a string.
    • When a numeric value of an integer or floating-point number is converted to a string, the string consists of numeric characters representing the numbers (the floating-point number also contains the exponential portion).
    • The array is converted to the string "array", so the contents of the array cannot be output through the echo () or print () function. Please refer to below for more tips.
    • The object is converted to the string "Object". If you need to print the object's member variables for debugging purposes, please read the following. If you want to get the name of the class to which the object is attached, use the function Get_class (). From PHP 5, if appropriate, you can use the __tostring () method.
    • The resource type is always converted to a string in the format "Resource ID #1", where 1 is the unique identity that PHP assigns to the resource at run time. If you want to get the type of the resource, use the function Get_resource_type ().
    • Null will be converted to an empty string.
As shown above, printing arrays, objects, or resources does not provide any useful information about the values themselves. See Functions Print_r () and Var_dump (), which are better ways to print values for debugging purposes.
You can convert the values of PHP to strings to store them permanently. This method is called serialization and can be done with the function serialize (). If you set up WDDX support when you install PHP, you can also serialize the value of PHP into an XML structure.


4. Casting an array (array)
    • For any type: integer, floating Point, String, Boolean, and resource, if you convert a value to an array, you will get a list of only one element (its subscript is 0), which is the value of this scalar.
    • If an object is converted to an array, the resulting array of elements is the property (member variable) of the object whose key name is the member variable name.
    • If you convert a value to an NULL array, you will get an empty set.

5. Convert to Objects (object)

If you convert an object to an object, it will not change. If any other type of value is converted to an object, an instance of the built-in class Stdclass will be created. If the value is null, the new instance is empty. Converting an array into an object causes the key name to be the property name and has a corresponding value. For any other value, a member variable named scalar will contain the value


6. Convert to resource (cannot convert)
Because resource type variables hold special handles for open files, database connections, graphics canvas areas, and so on, you cannot convert other types of values to resources.
PHP Type comparison table (see Manual Appendix P)
The table below shows the role of PHP types and comparison operators when they are loosely and rigorously compared. The supplemental material is also relevant to the relevant section of the type-juggling.
    • Attention
    • HTML forms do not pass integers, floating-point numbers, or Boolean values, they only pass strings. To detect if a string is not a number, you can use the Is_numeric () function.
    • When a variable $x is not defined, the use of an if ($x) results in a e_notice level error. Therefore, you might consider initializing the variable with the empty () or isset () function.

How to implement PHP coercion type conversion

Conversion format

Conversion results

Implementation method

(int), (integer)

To cast a different data type to an integral type

$a = "3"; $b = (int) $a; $c = (integer) $a;

(bool), (Boolean)

To cast a different data type to a Boolean type

$a = "3"; $b = (bool) $a; $c = (Boolean) $a;

(float), (double), (real)

Casting other data types to floating-point

$a = "3"; $b = (float) $a; $c = (double) $a; $d = (real) $a;

(string)

To cast another data type to a string

$a = 3; $b = (string) $a;

(array)

Casting additional data types to an array

$a = "3"; $b = (array) $a;

(object)

To cast other data types to an object

$a = "3"; $b = (object) $a;

Other data types are converted to integral type

< p>   class  

Target type

Conversion gauge

Floating-point

int

Rounded down, that is, instead of rounding out the floating-point data, just the part of the decimal, leaving only the integer part

Boolean

int

TRUE converts to integer number 1, FALSE to integer 0

String

Integral type

String is a pure integer number, converted to the corresponding integer number

The string is a decimal number, and when converted, it is removed from the back part, preserving the integer part

The string starts with an integer number, removes the integer number after it is converted, and then processes it according to rule 1

String starts with a decimal number, removes the back part of the decimal when converted, and then processes it by rule 2

String content is converted directly to 0 with a non-numeric start

Other data types are converted to floating-point type

Original type

Target type

Conversion rules

Integral type

Floating point Type

Convert integer data directly to floating-point type with values unchanged

Boolean type

Floating point Type

TRUE converts to floating-point number 1, FALSE to floating-point number 0

String

Floating point Type

The string is an integer number and is converted directly to the corresponding floating-point number

String starts with a number, removes the back part of the number when converted, and then processes it according to rule 1

The string begins with a decimal number, which directly removes the trailing part of the number, leaving only the number part

The string is converted directly to 0 at the beginning of non-digital content

Convert other data types to Boolean

Original type

Target type

Conversion rules

Integral type

Boolean type

0 convert to FALSE, nonzero for other integer numbers to TRUE

Floating point Type

Boolean type

0 conversion to FALSE, non-zero other floating-point numbers converted to TRUE

String

Boolean type

Null string or string content is zero converted to FALSE, and other strings are converted to TRUE

Null

Boolean type

Convert directly to FALSE

Array

Boolean type

Null array converted to FALSE, non-empty array converted to TRUE

Other data type conversions to an array

Original type

Target type

Conversion rules

Integer, floating-point, Boolean

String, Resource

Array

When these data types are cast to arrays, the resulting array contains only one data element, which is the pre-converted data, and the data type is the same as before the conversion

Object

Array

The name of the member variable of the object is converted as a key of each array element, and the value of each key in the converted array is null, if the member variable is private (private), the name of the converted key is "class name + member variable name", and if the member variable is public, the The name of the key after the change is the member variable name, if the member variable is protected (protected), the name of the converted key is "*+ member variable name"

Null

Array

Convert directly to an empty array

Converting other data types to objects

Original type

Target type

Conversion rules

Integral type, floating point type

Boolean, String

Object

When you convert another type variable to an object, a new property named "Scalar" is created, and the value of the original variable is stored in this property

Array

Object

When you convert an array to an object, the array's key is the name of the object member variable, and the value of each key is saved as an object member variable.

Null

Object

Convert directly to an empty object

Converting other data types to strings

Original type

Target type

Conversion rules

Integral type

String

Convert with double quotes directly around the integer data as the converted Result

Floating point Type

String

Convert with double quotes directly around floating-point data as the converted Result

Boolean type

String

TRUE to convert to string "1", FALSE to string "0"

Array

String

Convert directly to string "Array"

Object

String

Convert directly to string "Object"

Null

String

Convert directly to an empty string

PHP type conversion && type casting

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.