Document directory
- I. Introduction to types
- Ii. Boolean
- Iii. Integer type
- Iv. String
- 5. Array
PHP supports eight primitive types, including:
Four scalar types: Boolean, integer, float, and string );
Two composite types: array and object );
Two special types: Resource and null
You may also read some references about the double type. In fact, double and float are the same. For some historical reasons, these two names exist at the same time.
The type of a variable is generally not set by the programmer. To be exact, it is determined by PHP at runtime Based on the context used by the variable.
I. Introduction to types
Note: If you want to view the value and type of an expression, use var_dump ().
Note: If you just want to get an easy-to-understand expression of the type for debugging, use GetType (). To view a type, use the is_type function instead of GetType. The following are examples:
Code 1:
<? Php <br/> $ bool = true; // a Boolean <br/> $ STR = "foo"; // a string <br/> $ Int = 12; // an integer </P> <p> echo GetType ($ bool); // prints out "Boolean" <br/> echo GetType ($ Str ); // prints out "string" </P> <p> // if this is an integer, increment it by four <br/> If (is_int ($ INT )) {<br/> $ int + = 4; <br/>}</P> <p> // If $ bool is a string, print it out <br/> // (does not print out anything) <br/> If (is_string ($ B OOl) {<br/> echo "string: $ bool"; <br/>}< br/>?> <Br/>
If you want to forcibly convert a variable to a certain type, you can use the force conversion or settype () function for it.
Ii. Boolean
This is the simplest type. Boolean indicates the true value, which can be true or false. (Note: The boolean type is introduced in PHP 4)
To specify a Boolean value, use the keyword true or false. Both are case insensitive.
<? Php <br/> $ Foo = true; // assign the value true to $ Foo <br/>?>
You usually use some operators to return boolean values and pass them to process control.
/// = Is an operator which test <br/> // equality and returns a Boolean <br/> if ($ action = "show_version ") {<br/> echo "the version is 1.23"; <br/>}</P> <p> // This is not necessary... <br/> if ($ show_separators = true) {<br/> echo "<HR>/N "; <br/>}</P> <p> //... because you can simply type <br/> if ($ show_separators) {<br/> echo "<HR>/N"; <br/>}
To convert a value to a Boolean value explicitly, use (bool) or (Boolean) to forcibly convert the value. However, in many cases, forced conversion is not required, because this value is automatically converted when an operator, function, or flow control requires a Boolean parameter.
When converted to boolean, the following values are considered false:
Boolean value false, integer value 0, floating point value 0.0, blank string and string "0", array without member variables, object without Unit, Special Type null (including unset variables))
All other values are considered to be true (including any resources ).
Note:-1Like other non-zero values (both positive and negative values ),True!
Iii. Integer type
An integer is a number in the set Z = {...,-2,-1, 0, 1, 2.
The integer value can be specified in decimal, hexadecimal, or octal notation. An optional Symbol (-or +) can be added before ).
If the octal symbol is used, 0 must be added before the number, and 0x must be added before the hexadecimal symbol.
Code 1: integer expression
<? Php <br/> $ A = 1234; # decimal number <br/> $ A =-123; # a negative number <br/> $ A = 0123; # octal values (83 in decimal format) <br/> $ A = 0x1a; # hexadecimal values (26 in decimal format) <br/>?>
Literally, the formal structure of an integer variable can be:
<? Php <br/> decimal: [1-9] [0-9] * <br/> | 0 </P> <p> hexadecimal: 0 [XX] [0-9a-fa-f] + </P> <p> octal: 0 [0-7] + </P> <p> INTEGER: [+-]? Decimal <br/> | [+-]? Hexadecimal <br/> | [+-]? Octal <br/>?> <Br/>
The length of the integer is related to the platform, although the maximum value is usually about 2 billion (32-Bit Signed ). PHP does not support unsigned integers.
If you specify a number that exceeds the Integer Range, it will be interpreted as float. Similarly, if the calculation result exceeds the Integer Range, float is returned.
<? Php <br/> $ large_number = 2147483647; <br/> var_dump ($ large_number); <br/> // The output is int (2147483647) </P> <p> $ large_number = 2147483648; <br/> var_dump ($ large_number); <br/> // The output is float (2147483648) </P> <p> // It also applies to hexadecimal integers: <br/> var_dump (0x80000000); <br/> // The output is: float (2147483648) </P> <p> $ million = 1000000; <br/> $ large_number = 50000 * $ million; <br/> var_dump ($ large_number ); <br/> // output: Float (50000000000) <B R/>?>
PHP does not have the Division operator. 1/2 generates a floating point number of 0.5. You can discard the fractional part or use the round () function.
<? Php <br/> var_dump (25/7); // float (3.5714285714286) <br/> var_dump (INT) (25/7); // int (3) <br/> var_dump (round (25/7); // float (4) <br/>?>
To explicitly convert a value to an integer, use (INT) or (integer) to force the conversion. However, in most cases, no forced conversion is required, because the value is automatically converted when an integer parameter is required for the operator, function, or flow control. You can also convert a value to an integer using the intval () function.
1. Convert from boolean: false will generate 0, true will generate 1.
2. From floating point type conversion:
When the number is converted from a floating point number to an integer, the number is rounded (decimal places discarded ).
If the floating point number exceeds the Integer Range (usually +/-2.15e + 9 = 2 ^ 31), the result is uncertain, because there is not enough precision to make the floating point number give an exact integer result. In this case, there is no warning or even no notification!
Note: in Linux, the returned result is a minimum negative value (-2147483648), and in windows, the returned result is zero (0 ).
Note: Do not forcibly convert an unknown score to an integer, which sometimes leads to unexpected results.
<? Php <br/> echo (INT) (0.1 + 0.7) * 10); // display 7! <Br/>?>
Iv. String
String is a series of characters. In PHP, the character is the same as the byte, that is, there are a total of 256 different characters. This also implies that PHP does not support Unicode locally. For more information about Unicode support, see utf8_encode () and utf8_decode.
Note: php does not impose an implementation range on the size of a string, so there is no reason to worry about long strings.
Strings can be defined using three literal Methods: single quotes, double quotes, and delimiters.
4.1 single quotes
The simplest way to specify a simple string is to enclose it with single quotes (character.
To express a single quotation mark, you must use a backslash (/) to escape it, just like many other languages. If a backslash is required before single quotes or at the end of a string, two backslashes are required. Note that if you try to escape any other character, the backslash itself will be displayed! Therefore, you do not need to escape the backslash itself.
Note: in PHP 3, an e_notice warning is triggered.
Note: Unlike the other two syntaxes, variables and escape sequences in single quotes strings are not replaced by variable values.
<? Php <br/> echo 'this is a simple string '; </P> <p> echo 'you can also have embedded newlines in <br/> strings this way as it is <br/> okay to do '; </P> <p> // outputs: Arnold once said: "I'll be back" <br/> echo 'arnold once said: "I/'ll be back" '; </P> <p> // outputs: You deleted C :/*. *? <Br/> echo 'you deleted C ://*.*? '; </P> <p> // outputs: You deleted C :/*.*? <Br/> echo 'you deleted C :/*.*? '; </P> <p> // outputs: this will not expand:/n a newline <br/> echo 'this will not expand:/n a newline '; </P> <p> // outputs: variables do not $ expand $ either <br/> echo 'variables do not $ expand $ either '; <br/>?>
4.2 double quotation marks
If double quotation marks (") are used to enclose strings, PHP understands the escape sequence of more special characters:
Table 1: escape characters
Sequence |
Description |
/N |
Line feed (LF or ASCII character 0x0a (10 )) |
/R |
Press enter (Cr or ASCII character 0x0d (13 )) |
/T |
Horizontal tab (HT or ASCII character 0x09 (9 )) |
// |
Backslash |
/$ |
Dollar sign |
/" |
Double quotation marks |
/[0-7] {1, 3} |
This regular expression matches a character in the octal symbol. |
/X [0-9a-fa-f] {1, 2} |
This regular expression matches a character in the hexadecimal notation. |
In addition, if you try to escape any other characters, the backslash itself will be displayed! The most important aspect of a double quotation mark string is that the variable name is replaced by the variable value.
4.3 delimiters
Another method is to define the string using the delimiter syntax ("<"). An identifier should be provided after <, followed by a string, followed by the end string of the same identifier.
The end identifier must start from the first column of the row. Similarly, the identifier must follow the naming rules for any other tag in PHP: it can only contain letters, numbers, underscores (_), and must start with an underscore or a non-digit character.
Warning it is important to note that the row of the end identifier cannot contain any other character, except a semicolon. This especially means that the identifier cannot be indented, and there cannot be any spaces or tabs before or after the semicolon. It is also important to realize that the first character before the end identifier must be a line break defined in your operating system. For example, in a Macintosh system, it is/R.
If this rule is broken so that the end identifier is not "clean", it will not be regarded as the end identifier, and PHP will continue searching for it. If an end identifier cannot be found in this case, a syntax error occurs in the last line of the script.
The delimiter text is the same as the double quotation mark string, but it does not contain double quotation marks. This means that no escape quotation marks are required in the delimiter text, but the escape Code listed above can still be used. The variable is expanded, but when the complex variable is expressed in the delimiter text, you should also note the same as the string.
Code 1: delimiter string example
<? Php <br/> $ STR = <EOD <br/> example of string <br/> spanning multiple lines <br/> using heredoc syntax. <br/> EOD; </P> <p>/* more complex example, with variables. */<br/> class Foo <br/> {<br/> var $ Foo; <br/> var $ bar; </P> <p> function Foo () <br/>{< br/> $ this-> Foo = 'foo'; <br/> $ this-> bar = array ('bar1', 'bar2 ', 'bar3'); <br/>}</P> <p> $ Foo = new Foo (); <br/> $ name = 'myname'; </P> <p> echo <EOT <Br/> my name is "$ name ". I am printing some $ foo-> Foo. <br/> now, I am printing some {$ foo-> bar [1]}. <br/> This shoshould print a capital 'A':/x41 <br/> EOT; <br/>?>
4.4 variable Parsing
When a string is specified using double quotation marks or delimiters, the variables in the string are parsed.
There are two types of syntax: one is simple and the other is complex. Simple syntax is the most common and convenient. It provides methods for parsing variables, array values, or object attributes.
Complex syntax is introduced in PHP 4. You can enclose an expression in curly brackets.
If you encounter the dollar sign ($), the parser retrieves as many characters as possible to form a valid variable name. If you want to explicitly specify the end of a name, enclose the variable name in curly brackets.
<? Php <br/> $ beer = 'heineken'; <br/> echo "$ beer's taste is great"; // works, "'" is an invalid character for varnames <br/> echo "he drank some $ beers"; // won't work,'s is a valid character for varnames <br/> echo "he drank some $ {beer} s "; // Works <br/> echo "he drank some {$ beer} s"; // Works <br/>?>
You can also parse array indexes or object attributes. For an array index, the right square brackets (]) indicate the end of the index. Object Attributes apply the same rules as simple variables, even though they are not as skillful as variables.
<? Php <br/> // these examples are specific to using arrays inside of strings. <br/> // when outside of a string, always quote your array string keys <br/> // and do not use {braces} when outside of strings either. </P> <p> // Let's show all errors <br/> error_reporting (e_all ); </P> <p> $ fruits = array ('strawberry '=> 'red', 'bana' => 'yellow '); <br/> // works but note that this works differently outside strin G-quotes <br/> echo "a banana is $ fruits [banana]. "; <br/> // Works <br/> echo" a banana is {$ fruits ['bana']}. "; </P> <p> // works but PHP looks for a constant named banana first <br/> // as described below. <br/> echo "a banana is {$ fruits [banana]}. "; </P> <p> // won't work, use braces. this results in a parse error. <br/> echo "a banana is $ fruits ['bana']. "; </P> <p> // Works <br/> echo" a banana is ". $ fru Its ['bana']. ". "; </P> <p> // Works </P> <p> echo" this square is $ square-> width meters broad. "; <br/> // won't work. for a solution, see the complex syntax. <br/> echo "this square is $ square-> width00 centimeters broad. "; <br/>?>
4.5 complex syntax
It is not complicated because of the complex syntax, but because this method can contain complex expressions.
In fact, you can use this syntax to include any value in the namespace in a string. Write an expression in the same way as the string, and use {And} to include it. Because "{" cannot be escaped, this syntax is recognized only when $ is followed by {(use "{/$" or "/{$" to get a literal "{$ "). Some examples can be clearer:
<? Php <br/> // Let's show all errors <br/> error_reporting (e_all); </P> <p> $ great = 'fantastic '; </P> <p> // No. The output is: This is {fantastic} <br/> echo "this is {$ great }"; </P> <p> // yes. The output is: this is fantastic <br/> echo "this is {$ great }"; <br/> echo "this is $ {great }"; </P> <p> // Works <br/> echo "this square is {$ square-> width} 00 centimeters broad. "; </P> <p> // Works <br/> echo" This works: {$ arr [4] [3]} "; <br/> // This I S wrong for the same reason as $ Foo [bar] Is Wrong <br/> // outside a string. in otherwords, it will still work but <br/> // because PHP first looks for a constant named Foo, it will <br/> // throw an error of level e_notice (undefined constant ). <br/> echo "this is wrong: {$ arr [Foo] [3]}"; <br/> // works. when using multi-dimen1_arrays, always use <br/> // braces around arrays when inside of strings <Br/> echo "This works: {$ arr ['foo'] [3]}"; </P> <p> // works. <br/> echo "This works :". $ arr ['foo'] [3]; </P> <p> echo "You can even write {$ obj-> values [3]-> name }"; </P> <p> echo "this is the value of the VaR named $ name :{$ $ name }}"; <br/>?>
4.6 characters in the access string
The characters in the string can be accessed by specifying the offset of the expected character from scratch with curly brackets after the string.
Note: square brackets can still be used for backward compatibility. However, this syntax is not supported in PHP 4.
Code 2: some string examples
<? Php <br/> // get the first character of a string <br/> $ STR = 'this is a test. '; <br/> $ first = $ STR {0 }; <br/> // get the third character of a string <br/> $ third = $ STR {2 }; </P> <p> // get the last character of a string. <br/> $ STR = 'this is still a test. '; <br/> $ last =last STR {strlen ($ Str)-1 }; <br/>?>
4.7 practical functions and operators
Strings can be connected using the "." (vertex) operator. Note that the "+" (plus) operator cannot be used here. For more information, see string operators.
There are many practical functions to change the string.
For common functions, see the character string function library section. For Advanced Search and replacement, see regular expression functions (Perl and POSIX extensions ).
There are also URL string functions and encryption/Decryption string functions (mcrypt and mhash ).
4.8 String Conversion
You can use the (string) flag or the strval () function to convert a value to a string. When an expression requires a string, String Conversion is automatically completed within the expression range. For example, when you use the echo () or print () function, or compare a variable value with a string. Reading the sections about the type and type tricks in the manual helps to be clearer. See settype ().
The Boolean value true is converted to the string "1", and the value false is expressed as "" (an empty string ). In this way, you can compare boolean values with strings at will.
When an integer or floating-point number is converted to a string, the string represents these numeric values (floating-point numbers also contain the exponent part ).
The array is converted to the string "array", so you cannot output the array content through the ECHO () or print () function. Refer to the following for more tips.
The object is converted to the string "object ". If you need to print out the member variables of the object for debugging, read the following section. If you want to get the name of the class to which the object is attached, use the get_class () function ().
The resource type is converted to a string in the format of "resource ID #1", where 1 is the unique identifier specified for the resource by PHP at runtime. If you want to obtain the resource type, use the get_resource_type () function ().
Null is converted to a null string.
As shown above, printing arrays, objects, or resources does not provide you with any useful information about these values. See the print_r () and var_dump () functions. These are better ways to print values for debugging.
You can convert PHP values to strings to store them permanently. This method is called serialization. You can use the serialize () function to complete this operation. If you have created wddx support when installing PHP, you can also serialize PHP values into XML structures.
4.9 string to numeric value
When a string is evaluated as a number, the result type and value are determined according to the following rules.
If the string contains any of the characters ".", "E", or "e", it is evaluated as a float. Otherwise, it is treated as an integer.
This value is determined by the first part of the string. If a string starts with a valid number, use this number as its value. Otherwise, its value is 0 (0 ). Valid numeric data starts with an optional plus or minus sign, followed by one or more numbers (including decimal scores), followed by an optional index. An index is an "E" or "E" followed by one or more numbers.
<? Php <br/> $ Foo = 1 + "10.5"; // $ foo is float (11.5) <br/> $ Foo = 1 + "-1.3e3 "; // $ foo is float (-1299) <br/> $ Foo = 1 + "bob-1.3e3"; // $ foo is INTEGER (1) <br/> $ Foo = 1 + "bob3"; // $ foo is INTEGER (1) <br/> $ Foo = 1 + "10 small pigs "; // $ foo is INTEGER (11) <br/> $ Foo = 4 + "10.2 little piggies"; // $ foo is float (14.2) <br/> $ Foo = "10.0 pigs" + 1; // $ foo is float (11) <br/> $ Foo = "10.0 pigs" + 1.0; // $ foo is float (11) <br/>?>
If you want to test any examples in this section, you can copy and paste these examples and add the following line to see what will happen:<? Php <br/> echo "/$ Foo = $ Foo; type is". GetType ($ Foo). "<br/>/N"; <br/>?>
Do not expect to be encoded when converting a character into an integer (You may also do this in C ). If you want to convert between character encoding and character, use the ord () and CHR () functions.
5. Array
Arrays in PHP are actually an ordered graph. A graph is a type that maps values to keys. This type has been optimized in many ways, so you can use it as a real array, or a list (vector), a hash (an implementation of a graph), a dictionary, set, stack, queue, and more possibilities. Because another PHP array can be used as the value, and the tree can be easily simulated.
5.1 syntax
You can use the Array () language structure to create an array. It accepts a certain number of key => value parameter pairs separated by commas.
Array ([Key =>] <br/> value <br/> ,... <br/>) <br/> // key can be integer or string <br/> // value can be any value <br/>
<? Php <br/> $ arr = array ("foo" => "bar", 12 => true ); </P> <p> echo $ arr ["foo"]; // bar <br/> echo $ arr [12]; // 1 <br/>?>
The key can be an integer or string. If the key name is an integer standard expression, it is interpreted as an integer (for example, "8" will be interpreted as 8, and "08" will be interpreted as "08 "). The variable type under the array in PHP does not affect the array. There is only one type of array, which can contain both integer and string subscript.
The value can be any value.
<? Php <br/> $ arr = array ("somearray" => array (6 => 5, 13 => 9, "a" => 42 )); </P> <p> echo $ arr ["somearray"] [6]; // 5 <br/> echo $ arr ["somearray"] [13]; // 9 <br/> echo $ arr ["somearray"] ["A"]; // 42 <br/>?>
If no key name is specified for the given value, the current maximum integer index value is used, and the new key name is the value plus one. If the specified key name already has a value, the value will be overwritten.
<? Php <br/> // This array is the same... <br/> array (5 => 43, 32, 56, "B" => 12); </P> <p> //... this array <br/> array (5 => 43, 6 => 32, 7 => 56, "B" => 12); <br/>?>
Warning the above index generation method has changed since PHP 4.3.0. If you add a new value to an array whose current maximum key name is negative, the newly generated index will be zero (0 ). Previously, the newly generated index is the current maximum index plus one, which is the same as the positive index.
Use true as the key name to make integer 1 A key name. Use false as the key name to make integer 0 the key name. Using null as the key name is equivalent to using a null string. Use an empty string as the key name to create (or overwrite) a new value with an empty string as the key name, which is different from the empty square brackets.
Arrays and objects cannot be used as key names. This will cause a warning: Illegal offset type.
5.2 create/modify with square brackets
You can explicitly set a value to change an existing array.
This is achieved by specifying a key name in square brackets to assign values to the array. You can also omit the key name. In this case, add an empty square brackets ("[]") to the variable name.
$ Arr [Key] = value; <br/> $ arr [] = value; <br/> // key can be integer or string <br/> // value can be any value. <Br/>
If $ arr does not exist, a new one is created. This is also a replacement method for defining arrays. To change a value, just assign it a new value. If you want to delete a key/value pair, you need to use unset () for it ().
<? Php <br/> $ arr = array (5 => 1, 12 => 2); <br/> $ arr [] = 56; // This is the same as $ arr [13] = 56; <br/> // at this point of the script <br/> $ arr ["X"] = 42; // This adds a new element to <br/> // The array with key "X" <br/> unset ($ arr [5]); // This removes the element from the array <br/> unset ($ ARR); // This deletes the whole array <br/>?>
Note: As described above, if you provide square brackets but do not specify a key name, the current maximum integer index value will be taken. The new key name will be the value + 1. If no integer index exists, the key name is 0. If the specified key name already has a value, the value will be overwritten.
Note that the maximum integer key used here is not necessarily in the array currently. It only needs to exist after the index is re-generated in the last array. The following example shows how:
<? Php <br/> // create a simple array <br/> $ array = array (1, 2, 3, 4, 5 ); <br/> print_r ($ array); </P> <p> // delete all the units in the list, but keep the structure of the array <br/> foreach ($ array as $ I =>$ value) {<br/> unset ($ array [$ I]); <br/>}< br/> print_r ($ array); </P> <p> // Add a unit (note that the new key name is 5, instead of the possible 0) <br/> $ array [] = 6; <br/> print_r ($ array); </P> <p> // re-index: <br/> $ array = array_values ($ array); <br/> $ array [] = 7; <br/> print_r ($ array); <br/>?>
The above example will generate the following output:
Array( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5)Array()Array( [5] => 6)Array( [0] => 6 [1] => 7)
5.3 practical functionsThere are quite a few practical functions acting on the array. The unset () function allows you to cancel the key name in an array. Note that the array will not rebuild the index.
<? PHP $ A = array (1 => 'one', 2 => 'two', 3 => 'three '); unset ($ A [2]); /* generates an array, defined as $ A = array (1 => 'one', 3 => 'three '); instead of $ A = array (1 => 'one', 2 => 'three '); */$ B = array_values ($ ); // now B is array (1 => 'one', 2 => 'three ')?>
The foreach control structure is specially used for arrays. It provides a simple method to traverse arrays.