Chapter 1 PHP Quick Start
PHP variables have three styles.
Short style: the PHP variable is the same as the form domain name in the HTML form. $ Tireqty
Moderate style: $ _ post ["tireqty"] $ _ get $ _ Request
Long style: $ http_post_vars ['tireqty '] $ http_get_vars (may disappear)
The dot (.) is the string connector echo $ tireqty. 'tires <br/> ';
If $ tireqty is not an array variable, you can also write it as Echo "$ tireqty tires <br/> ';
PHP has a special type, resource variable, which generally represents external resources (such as database connections) and cannot directly operate a resource variable.
PHP is weakly typed. You can determine the type of a variable at any time based on the value stored in the variable.
For example, $ Total = 0.00 (float type)
$ Total = 'hello' (string type)
You can also perform type conversion:
$ A1 = 0
$ A2 = (float) $ A1
The value of a variable can be used as the name of another variable:
$ Varname = 'a1 ';
$ Varname = 5; <=> (these two statements are equivalent to) $1 = 5;
Declare constant: Define ('price', 100 );
Use constant: Echo price; (Note that there is no $ above)
Constants can only store Boolean, integer, floating point, or string data.
PHP also has the concept of "Reference.
$ A = 5;
$ B = & $;
$ A = 7;
At this time, the value of B will also change to 7.
Unset ($ A) resets the address pointed to by $ A, which breaks the connection between $ A and 7 stored in memory, but does not change $ B (7)
0 = '0' returns true
0 = '0' returns false (the three equal signs indicate the constant operation. The values are equal and the types are the same)
There are still issues! =
Error suppression operator @
$ A = @ (57/0 );
This prevents warnings. Otherwise, a warning is generated, except for 0.
Execution operator (reverse single quotes '')
$ Out = 'LS-la ';
Echo '<PRE>'. $ out. '</PRE>'
A directory list can be displayed in the browser.
Array OPERATOR:
$ A + $ B
$ A ==$ B; $ A ===$ B; $! = $ B; $ A <> $ B (true if $ A and $ B are not equivalent); $! ==$ B;
GetType ($ A); you can get a description string of the $ A type.
Settype ($ A, 'double'); set $ A to double-precision.
Is_array (); is_double ();...... You can check whether the variable belongs to a certain type, and return true or false.
The control structure is basically the same as that of C.
If/switch/while/For/foreach
If ($ Var = 0) {somecode;} can be replaced with the following structure:
If ($ Var = ):
Somecode;
Endif;
You can use declare to set the code block execution instructions.
Chapter 2 data storage and retrieval
Fopen ("$ document_root/../order.txt", 'w'); // you can use a backslash to represent a directory, but it can only be used on Windows. (Fclose ($ FP ))
Fopen ("order.txt", 'w', true); // search for the order.txt file in php的de_path.
If the file name starts with http: //, fopen establishes an HTTP connection to the specified server and returns a pointer to the HTTP response.
@ $ Fp = fopen ("/SSS/test.txt", 'w ');
If (! $ FP)
{
// An error occurred while processing the opened file. If @ is not added before $ FP, an error message will appear in PHP.
}
Fwrite ($ FP, $ outputstring [, int length]); (fwrite is equivalent to fputs)
PhP5 is added:
Int file_put_contents (string filename, string data [, int flags [, resource context]) can be used to directly operate files without fopen (corresponding to file_get_contents ())
The fgetss function is similar to fgets, but it can filter some special flags.
Fgetcvs can use a separator as the branch of the file.
Fread () can read any length of bytes.
File () readfile () and so on can read the entire file
File_exists () check whether the file exists.
Filesize () determines the file size.
Unlink () delete an object
Rewind (), fseek (), and ftell () are located in the file.
Flock lock before using files
Chapter 3 Use Arrays
Initialize the numeric index array: $ products = array ('tires ', 'oil', 'spark ');
$ Numbers = range (10, 15); Create an array of 10-15 $ odds = range (1, 10, 2); 2 represents the stride.
Foreach ($ arr, as $ ELEM)
Echo $ ELEM;
$ Arr is an array and ELEM is a single element.
Initialization of related Arrays: $ prices = array ('tires' => 100, 'oil '=> 10, 'spark' => 4 );
$ Prices = array ('tires' => 100); $ Prices ['oil '] = 10;
Traverse related Arrays:
Foreach ($ prices as $ key => $ value)
Echo $ key. '=>'. $ value. '<br/> ';
You can also use List () and each () to traverse the array content. Each () returns the current element of the array and uses the next element as the current element. (If you want to use the each () function for $ price again, you must use reset ($ price) to reset the array to the beginning .)
While ($ ELEM = each ($ price) {code ;}
List ($ product, $ price) = each ($ price); // The Code splits the $ price array into two arrays, $ product stores only the first element in $ price, and then $ price stores the rest.
Array Operation: $ A + $ B, array B will be appended to a, but any element with a keyword conflict will not be added.
$ A = $ B. arrays A and B contain the same elements (the order is not necessarily the same)
$ A ===$ B. arrays A and B contain the same elements and have the same order.
The array element can be another array, that is, a multi-dimensional array.
$ Products = array (Array ('till', "tires ', 100 ),
Array ('oil ', 'oil', 10 ),
Array ('spk', 'spark ', 4 ));
Echo $ products [1] [0];
Sort ($ products); sorts arrays.
Sort ($ products, sort_numric); the sorting type is numerical sorting.
Asort () and ksort () can sort "related arrays. (Asort is sorted by element values, and ksort is sorted by keywords .)
Rsort (), arsort (), and krsort () are sorted in descending order.
To sort two-dimensional arrays, You need to customize the sorting method:
Function compare ($ X, $ Y ){
If (...) return 0;
Else if (...) Return-1;
Else return 1;
}
Usort ($ products, 'company ');
In usort, u represents user, indicating the comparison function to be customized. There are also uasort () and uksort ().
Shuffle () can be used to randomly sort the elements in the array. Array_reverse () can reverse sort arrays.
Load an array from a file:
$ Orders = file ("$ document_root/../orders.txt ");
$ Number = count ($ orders); // gets the number of arrays. Each element in orders is each row in the original file.
For ($ I = 0; $ I <$ number; $ I ++)
{Echo $ orders [$ I];}
You can use $ line = explode ("/T", $ orders [$ I]) to separate each row into n elements. The separator is "/t ". these elements are stored in $ line.
Intval () can extract numbers from strings.
Each array has an internal pointer pointing to the current element in the array. When the function each () is used, the pointer is used indirectly, but the pointer can be directly used and operated.
Current ($ array_name); returns the elements indicated by the current pointer.
Next () returns the next, end () returns the last, Prev () returns the previous, reset () returns the first element, and sets the pointer to the corresponding position.
Apply any function to each element of the array: array_walk ()
Function my_print ($ value) {echo "$ value <br/>";} // This custom function can have a maximum of three parameters: value, key, and userdata, userdata is passed through the 3rd parameters of array_walk.
Array_walk ($ array, 'My _ print ');
This is similar to for_each () in the C ++ standard library ().
Count the number of array elements: Count (), sizeof (), and array_count_values ().
Count () is the same as sizeof (), and returns the number of array elements.
Array_count_values () can be used to count the number of occurrences of each specific value in the array (the base set of the array ). This function returns an array containing the frequency table.
Extract () allows you to create a series of scalar variables through an array. The name of the title variable is the name of the keyword in the array.
For example, $ array = array ('key1' => 'value1', 'key2' => 'value2 ');
Extract ($ array); // automatically creates two variables, $ key1 and $ key2
Echo "$ key1 $ key2"; // The value is value1 value2.
Extract has three parameters. The second parameter extract_type specifies how to handle conflicts. For example, a variable with the same name already extract (the default operation is overwrite ).
Chapter 4 string operations and Regular Expressions
The mail function can directly send emails. Its prototype is:
Bool mail (string to, string subject, string message,
String [additional_headers [, string additional_parameters]);
The TRIM () function removes spaces at the start and end positions of the string and returns the result string. (Here are spaces in a broad sense, including line breaks, tabs, string Terminators, and spaces ). Its second parameter can also specify the special characters to be filtered. (Ltrim and rtrim remove spaces on the left or right, respectively ).
The nl2br () can replace the linefeed in the string with <br/>.
You can use printf () or sprintf () to format some displayed strings.
To print the "%" symbol with printf, you must use "% ".
Printf ("total amount is % 2/$ D and % 1/$ D, $ total, $ total_ship );
"2/$" means to replace the second parameter in the parameter list (you only need to add the parameter location Directly after "%" and end with the $ symbol ).
Vprintf () and vsprintf () also exist ().
The strtoupper () string is converted to uppercase, And the strtolower () is converted to lowercase. If the first character of the string is a letter, the string is converted to uppercase, ucwords () converts the first letter of each word into uppercase letters.
Addslashes () and stripslashes () can format strings for storage. Such as quotation marks, backslash, and null. Therefore, escape the characters that may be interpreted as special characters into common characters before storage.
Explode divides the string into small parts based on a specified delimiter and returns the small parts to an array.
$ Email_array = explode ('@', $ email );
Implode () is equivalent to join () and has the opposite effect as explode.
Strtok () can also split strings into small pieces.
Substr () returns a substring.
Strcmp (), strcasecmp (), and strnatcmp () are used to sort strings. Strnatcmp () is a "natural sorting" based on people's habits (2 will be smaller than 12, and 2 will be 12 in the Lexicographic Order ).
Strstr (), strchr (), strrchr (), stristr () can all be searched for strings in the string.
Strstr is equivalent to strchr.
Strpos () and strrpos () are used to locate the substring and run faster than strstr.
Str_replace () searches for substrings in a string and replaces the searched substrings.
Substr_replace () replaces the substring at the specified position in the string.
PHP supports POSIX and Perl-style regular syntax. The default value is POSIX, but the Perl style can be used by compiling PCRE.
Search string: ereg () and eregi ().
Int ereg (string pattern, string SEARCH, array [matches]); // eregi () is case insensitive.
Replace the substring: ereg_replace (). (Eregi_replace ()).
Split string: Split ().
Generally, for the same function, the running efficiency of the regular expression function is lower than that of the string function. If the application is simple enough, it is best to use a string expression.