Note about arrays, strings in PHP

Source: Internet
Author: User
Tags first string http file upload md5 encryption rtrim sha1 sha1 encryption strcmp
this time, Ben K takes a look at some of the considerations and functions (methods) for arrays, strings in PHP.

One, the array in PHP

(i) Introduction to arrays in PHP

the array type is one of PHP two composite data types. depending on the subscript, the array in PHP can be divided into associative arrays and indexed arrays : The former refers to the subscript string format, each subscript string corresponds to the value of the array one by one, the latter subscript is a number, and the array subscript in JS is the same, But there are some rules that are far from JS (described later).

The following five articles about associative arrays and indexed arrays, and their differences from arrays in JS, can be broadly summarized as follows:

  1. In an array, an indexed array and an associative array can exist at the same time

Array (=>4, "four");

  2, in the array, all the indexed array, if not specified, will be stripped of the associated items, the default growth (that is, the associative array does not occupy the index bit)

Array (=>4,5,6, "four"); --1,2,3,5,6 Index 0 1 2 3 4, respectively

  3. If the key of the associative array is a pure decimal integer string, the number is converted to the index value of the indexed array

Array (=>4, "9"); --1 2 3 4 indexes 0 1 2 9, respectively

  4. If you manually specify the key of the associative array, the subscript of the indexed array, and if it is repeated with the previous key or subscript, then the value specified will overwrite the previous value

Array ("One" =>5, "one" =>6)-print array 1 2 "one" =>6

  5, if the index array is manually specified subscript, then the subsequent self-growth subscript, according to the previous subscript maximum, followed by growth

Array (=>4,5, "9"); --1 2 3 4 5 indexes 0 1 2 9 10, respectively

Second, it is the way arrays are declared in PHP. There are three types of array declarations in PHP, such as the following code, which are direct assignment declarations, array declarations,[] declarations . It is important to note that the third type of declaration is actually PHP5.4 version after the addition , you must first check the use of the PHP version.

$arr [] = 4;  Direct Assignment Declaration $arr = [1,2,3,4]; [] Declaration $arr = Array (1,2,3,4); Array declaration

There are 4 main ways to traverse an array in PHP, using a for loop to iterate through an array, a Foreach loop to iterate through an array, a list () each (), and an array pointer to iterate through an array. The detailed method K will be described in another blog post, please look forward to.

Finally, there are several hyper-global arrays involved in the PHP array. The so-called hyper-global, is that can be anywhere, any scope without declaration, directly can be used by several system arrays, which exists because of the scope of the PHP scope of the variable range restrictions (PHP this is really a pit). The following section of the note code, for everyone to make a reference.

/* * "Hyper global Array" * Hyper global Array, hyper global variable, predefined array, predefined variable--that's all it is. PHP gives us a set of hyper-global features that contain powerful Array. can be anywhere, any scope no need to declare, direct use!!     is not subject to any scope restrictions.        * 1 server variable: $_server * Returns all kinds of information including browser header information, path, script and server System! 2 environment variable: $_ENV * Change the system environment variable to an array in PHP.     is $_env;     * PHP By default is to turn off this global array, if required to use, you need to modify the php.ini Wenjiang in the variable_order= "GPSC", changed to EGPSC;     * However, there will be a system performance loss after modification, which is not recommended by the Government.     * You can use the getenv () function instead of global variables to take out the values of each system environment variable. * Phpinfo (); function, which contains various information about PHP, where the enviroment plate is a system environment variable, you can use GETEVN (), and take out each of these values.!!! 3 HTTP Get variable: $_get * Gets data submitted by the foreground by Get Method!!!! 4 HHTP Post variable: $_post * Gets the data submitted by the foreground via post 5 REQUEST variable: $_request * includes $_get/$_post/$_cookie three * due to possible simultaneous package        Including get post, may cause key conflicts, and efficiency is not high, so not used frequently!!! 6 http File Upload variable: $_files * An array of items uploaded to the current script via the HTTP POST Method 7 http Cookies:$_cookie * Fetch COOKIE information from the page!!!!      8 Session Variable: $_session * takes information stored in session 9 global variable: $GLOBALS * contains 8 global arrays above * You can also append subscripts to the $globals array to create global variables */

(ii) Common functions in PHP arrays

When it comes to the functions of arrays in PHP, we first need to remind the comrades from JS that the"function" of the array in PHP is the same as the "method" of the array in JS, which refers to the behavior of dealing with arrays. This part of the function, because of its huge content, first recommend that you look at the Help document (). Here are some notes on the array functions in PHP that are recorded in K, which you can paste into the editor and cancel/set comments to directly experience.

$arr = ["One" =>1,4,7, "9" =>10, "haha" = "haha", 4];    Returns the array of all values (arrays) Var_dump (Array_values ($arr));    Returns all the keys (arrays) of the array var_dump (Array_keys ($arr));    Detects if the array contains a value (Boolean) #参数 # The value to be queried, array [, true (= = =)/false (= =)]var_dump (In_array (1, $arr, true));    Swaps the keys and values (arrays) in the array var_dump (Array_flip ($arr)); Flipping an array (array) #参数 # array [, True (preserving the match of the index array's subscript to the value)/false (rollover value, key not retained)] #无论ture/false, does not affect associative arrays, and associative arrays always retain #var_dump (Array_    Reverse ($arr, TRUE));    Counts the number of array elements (shaping) Var_dump (count ($arr, 0)); Count the number of occurrences of each value in the array (array) var_dump (Array_count_values ($arr)); Do not use the system function to realize the function of array_count_values * * idea * 1, there is an empty array: key = = The value of the original array = = number of occurrences of each value of the original array * 2, traverse the original array, remove each value in the original array * 3, detect Whether the value being fetched has a key with the same name in the new array * if: The description finds a value that duplicates the new value now, then the value of this key in the new array is +1; * If none: Description Until now, there are no duplicates of the new value, then create a new     The key with the same name, and the value is 1.    *//* $arr 1 = [0,2,5,7,9,4,2,1,5,7,1,0,1,1,1,1,1,2,4,4,5,7,7,4,3,2,4,6,8,5,3];    $arr 2 = array ();        foreach ($arr 1 as $key 1=> $item 1) {$isHas = FALSE;//flag variable!!! foreach ($arr 2 as $key 2=> $iTEM2) {if ($key 2== $item 1) {$arr 2[$item 1]++;            $isHas = TRUE;    }} if (! $isHas) $arr 2[$item 1]=1;    } var_dump ($arr 2); *///the duplicate value in the divisor group//Var_dump (Array_unique ($arr)); Filter each value in the array */* do not pass the callback function: filter out all null values (0, "", NULL, False, "0", []) * callback function: The following *///var_dump (Array_filter ($arr, function ($nu        m) {//if ($num >4) {//return true;//}else{//return false;//}//}));    Each value of an array is processed by a callback function.    When executed, the callback function is passed to two parameters, which are value key, and then the value and key can be processed in the callback function! However, when it comes to modifying values, you must pass the address! Var_dump (Array_walk ($funcname))///* each value of the array is referred to the callback function for mapping processing array_map (): The first parameter is a callback function, the second parameter is a number of >=1 arrays, you can Pass several parameters to the callback function, which represents a value for each array, can process the returned value, and return it by return after processing, then the value of the new arrays is the value of return (*/$a =[1,2,3,4,5]; $b =[1,2,3,4];        Var_dump (Array_map (function ($value 1, $value 2) {return $value 1+ $value 2;        }, $a, $b)); /* * Array_walk and array_map similarities and differences * Both can iterate through the array, re-process each value of the array with a callback function * different points * 1, walk can only pass an array, the callback function accepts the value and key of the array, map can pass multiple arrays, the callback function accepts the value of each array * 2, walk directly modifies the original array; map does not modify the original array, the new array returns * 3, walk can pass a rest parameter to the callback function; map     Can only pass the value of the array * 4, processing mode, walk if you need to change the value of the original array, you need to pass the address in the callback function, directly modify the value of the variable; map is to modify the value of the new array by returning the new value with return. *//* * can pass in the second argument and control what sort.     The second parameter is 1, which means sorting by numbers; 2, which is sorted by ASCII; Sort is automatically detected by default--array sorting (ascending) Rsort--Reverse Array (descending) usort--sort the values in the array using a user-defined comparison function * The following three functions are commonly used for associative array sorting, using the same asort-array sorting and preserving the index relationship (associative array ordering) Arsort--Reverse sorting the array and keep the index relationship Uasort--user-defined comparison functions are sorted by array Order and keep the index associated * ksort--the array is sorted by key name Krsort--the array is reversed by key name Uksort--Sorts the key names in the array using a user-defined comparison function * Natural sorting, numbers according to 0-9, letters      Sort by A-Z * the following two functions will be sorted by nature, and key-value associations will be preserved when sorting natsort--Sort natcasesort with "natural sort" algorithm----sorting by "natural sort" algorithm for case-insensitive alphabetical sorting of groups     * Sort multiple arrays or multidimensional arrays. * First parameter: The first array must be selected, followed by optional parameters * Sort_string/sort_numberic by string or number * SORT_DESC/SORT_ASC ascending order * collation, first array first, After the array, according to the relationship with the first array, a column of the movement of a column * * If you sort multiple arrays, you need to maintain multiple number of leader degree consistent Array_multisort--sorting multiple arrays or multidimensional arrays */$arr = [1,2,3,4, 9,7,6, 10,22]; Sort ($arr);//Rsort ($arr);//Usort ($arr, function ($a, $b) {#同JS中数组sort//return-$a + $b;//});//Asor T ($arr);/*[does not change the original array] * array array_slice (array $array, int $offset [, int $length = NULL [, bool $preserve _keys = FAL SE]]) * parameter one: array, required * parameter two: From the beginning of the first intercept, required, negative number indicates from the right of the first few (in accordance with the default order of the array, including the association and index, rather than subscript) * parameter three: intercept length, optional, default Select all * Parameter four: Indicates whether to keep the key Value Association, optional, default index re-beat, for False,true to keep Association * *///$arr 1 = array_slice ($arr, 3,2);//Var_dump ($arr 1);/*[change original array] * Array arr Ay_splice (array & $input, int $offset [, int $length = 0 [, mixed $replacement]]) * Return value: deleted array * parameter one: address of the array        , it will change the original array * parameter two: From the beginning of the first delete or replace * parameter three: the length of the deletion or replacement * parameter four: null represents the delete operation, the incoming content represents the new value of the replacement operation * */$arr 2 = Array_splice ($arr, 4);    Var_dump ($arr 2);     /* * array_combine-creates an array with the value of an array as its key name, and the value of another array as its value * parameter one: An array as a key parameter two: an array of values * "two arrays must be consistent, otherwise warning, return false"     */* Merge multiple Arrays * array array_merge (array $array 1 [, Array $ ...]) * Merging multiple arrays, if an associated key value with the same name appears in multiple groups, then theCover the front of * *///* Two arrays Intersection * array array_intersect (array $array 1, array $array 2 [, array $ ...])     * Multiple arrays are intersected, the result retains the key value Association of the first array histograms */*/* Two array de-difference set * array Array_diff (array $array 1, array $array 2 [, array $ ...])     * Takes out multiple arrays, contains in the first array, but does not contain values in the other array, retains the key value Association of the first array * *//* * mixed Array_pop (array & $array)//delete the last value of the array, and return this value * int Array_push (array & $array, mixed $var [, mixed $ ...] The end of the array is put in one or more values, returning the number of elements of the array after processing * mixed Array_shift (array & $array)//delete the first value of the array, return this value * int Array_unshi FT (array & $array, mixed $var [, mixed $ ...] The array begins with one or more values, returning the number of array elements processed * */* * Mixed Array_rand (array $input [, int $num _req = 1]) * Randomly extracts one or more key names from an array, two arguments Empty, means pumping one, passing in the number of sub-notation to draw a few * */* * BOOL Shuffle (array & $array) * Randomly scrambled array order, directly modify the original array * */

B. Strings in PHP

(i) Introduction to Strings in PHP

The string in PHP is one of PHP's four basic data Types .

First of all, let's talk about how the string is declared in PHP. There are three ways to declare a string in PHP, which is declared by "", "", and by identifier ( detail visible ).

Second, to follow you in the form of code notes to focus on the various output functions in PHP, note the following.

    /* * "Various output functions" * 1, Echo (pure output, no return): outputs the content directly.     can be a function or instruction usage, instruction usage can print multiple parameters (comma split), function usage can only print one parameter.     * 2, print (basic use): There are functions and instructions, but two can not pass multiple parameters; There is a return value, the return value is always true. * 3, Print_r: When you print arrays and objects, the matching of keys and values is displayed in a certain format.     When Print_r prints an array, the array pointer is moved to the last one.     * 4, Var_dump: Debugging dedicated, display the type of printing, value and other information, when the array object is printed, the display key value matching is indented, you can pass in multiple parameters, while printing.     * 5, Die: equivalent to exit, output information and end the current script, you can not output information. * 6, printf: Print the content and format the variable output. First parameter: The string content to be printed, with multiple placeholders, and the second to multiple arguments: the variable corresponding to the placeholder one by one.     The following variables are output in the form of placeholders, in turn.     * 7, sprintf: Using the same as printf, just not the output statement, but the result of the conversion is assigned to a variable. * * [Common placeholder] percent return percentage symbol%b binary%c character%d in accordance with ASCII value decimal number%e can be renewed     Number method (such as 1.5e3)%u unsigned decimal number%f or%f floating-point numbers *-and floating-point numbers, which are reserved by default for six decimal places * percent sign and F can be inserted between a number to indicate the degree of accuracy.     * Integer portion of the number, representing the exact total width (integer + decimal + total number of decimal places).     * The fractional part of the number indicates that several decimals are reserved for rounding.     * If the width of the setting is less than the actual width, the setting is not valid; If the width is greater than the actual width, the left space is complementary.     * For example: $num = 10.12345;   * printf ("123%10.2f", $num); --10.12 * printf ("123%010.2f", $num);    -0000010.12%o    Octal number    %s string%x or%x hexadecimal number */ 

(ii) Common functions in PHP

Here, the recommendation for K is the same as the above array, and it is also recommended that you read the Help document first (). Below, K still in the way of code notes to the comrades to introduce the common functions in PHP.

    /* TRIM (): Remove spaces at both ends of the string; * LTrim (): Delete the space at the left of the string; * RTrim (): Delete the space at the right end of the string; * You can pass in the second argument to delete the related characters on both sides.     * from both sides of the string, start looking inward to find the character that appears in the second argument, and delete it as soon as it is found, until the first character that does not appear is encountered.        * The second character constant is written as "\t\n\r\0\x0b", which is used to delete all whitespace related symbols.          "" (ASCII (0x20)), plain space.          "\ T" (ASCII 9 (0x09)), tab.          "\ n" (ASCII (0x0A)), line break.          "\ R" (ASCII (0x0D)), carriage return.          "\" (ASCII 0 (0x00)), null byte character.     "\x0b" (ASCII One (0x0B)), Vertical tab. * * * * * $str = "1 2 3 4"; Echo $str. "    \ n "; Echo LTrim ($STR). " \ n "; Echo RTrim ($STR)." \ n "; echo Trim ($STR)." \ n "; echo Trim ($str," 43 ")."    \ n ";     /* * STR_PAD (): Fills the string to the specified length; * Parameter one: The string to be populated, required.     * Parameter two: You need to fill the string to how long, must be selected.     *---> If the length is less than or equal to the string, no effect will occur.     * Parameter three: text that needs to be filled, optional.     *---> Padding with spaces by default.     * Parameter four: on which side of the string to fill, optional.     *--->str_pad_both:2 *--->str_pad_left:0 *--->str_pad_right:1 *---> Default padding on the right, if you choose BOTH, start with the right.    */$STR 1 = "ABCD"; Echo Str_pad ($str 1, one, "", Str_pad_both), Echo Str_pad ($str 1, 11, "(Str_pad_left), Echo Str_pad ($str 1, one, "a", str_pad_right);     /* * Strtolower (): Converts all characters to lowercase * strtoupper (): Converts all characters to uppercase * The above two are commonly used for case-insensitive pairs. * * Ucfirst (): Converts the first letter of the string to uppercase * Ucwords (): The first letter of each word of the string is converted to uppercase * After the two are only responsible for the first letter, and regardless of the case of the other letters, if only the first letter uppercase, usually with Strtolower () first the word     The parent turns into lowercase.     * */* HTML-related functions: * 1, NL2BR (): Converts all line breaks in a string to <br> * 2, Htmlspecialchars (): Converts symbols in HTML to entity content.        * &:&amp;     ":&quot;     * ':& #039;      <:&lt;      * >:&gt;     Space:&nbsp;     * After turning into a special character, no need to turn back, the browser will automatically resolve to the corresponding label symbol. * 3. Delete all HTML tags in the string; * Parameter 1: string to filter HTML tags; * parameter 2: Allow existing HTML tags: strip_tags ($str, "<b><s><u>");     R in this string, there are <b><s><u> three tags, all the others are deleted.  * * *//* "common string Function" *1.strrev ($STR): Flip string; "12345"--"54321"; *2.strlen ($STR): Gets the number of characters in a string, Chinese = three characters *mb_strlen ($STR): Measures the length of a multibyte string, regardless of the length of both English and Chinese; * {Many string functions in PHP are prefixed with ' mb_ ', Specifically for manipulating Chinese multibyte Strings} *3.number_format (): A floating-point number is required to be formatted as a string. * Parameter 1: required format for floatingNumber of points, required. * Parameter 2: Retain several decimals (rounded), default is not reserved; * Parameter 3: The symbol of the decimal point, the default is "."; * Parameter 4: The display symbol of the thousand character: Default is ","; *4.md5 ()/SHA1 (): Encrypt the string using MD5 encryption algorithm and SHA1 encryption algorithm respectively; */$str = "ABCDEFG hahaha";//a Kanji three characters, one word selector echo Strrev ($STR), echo "<br/>", Echo strlen ($STR);//String length 16echo "<br/>"; Echo Mb_strlen ($STR);// String length 10echo "<br/>", Echo Number_format (12399.4567,4, "/", "-"), echo "<br/>", Echo MD5 ($STR); echo "<br/ > "; Echo SHA1 ($STR); echo" <br/> "; Echo sha1 ($STR) = =" 527e8bad76c863b8903c51f7eedad006678d5f96 ";/*" String comparison "* 1. Comparison operators can be compared: * < > = =: If both sides are strings, the first ASCII value is compared, * if the side is a number, then the string is converted to a number after the pair! * (important) 2.strcmp ("$str 1", "$str 2"): Comparison of two strings, case-sensitive, $str 1> $str 2-->1; $str 1< $str 2-->-1 $str 1== $str 2-->0 * 3.STRNCMP ("$str 1", "$str 2", int): The comparison is exactly the same as strcmp, except for a required parameter 3, which indicates the length of the comparison string, strncmp ("Asdsa", "ADSA", 2), Compare only the first two characters of the first two strings, and if you compare kanji strings, a Chinese character is three characters; * (important) 4.strcasecmp ("$str 1", "$str 2") compares a full string of strings, not case sensitive; * 5.STRNATCMP ("$str 1", "$ STR2 "): Sort the strings according to the natural sorting algorithm; * STRNATCMP (" 10 ","2"): 10>2, return 1; * strcmp ("10", "2"): Sorted by ASCII, 1&LT;2, return-1, both equal = 0, without any difference. *6. Similar_text (): Returns the similarity of two strings (the number of two string matching characters); * */Var_dump ("a" <1);//"A"-->0; Var_dump (strcmp ("A", "a")),//-1 Var_dump (strcmp ("5", "5"),//0 Var_dump (strncmp ("Aaer", "AACC", 2));//0 Var_dump ( STRNCMP ("Zhang and", "Zhang San", 2)),//0 var_dump ("ABCD", "ABCD"), strcasecmp//0 (Var_dump ("strnatcmp", "i10")), I2//1 (   Similar_text ("123", "234"));//The length of the same character//"Common string manipulation function" * 1.explode (): Use the specified delimiter to separate the string into arrays; * Parameter 1: what delimiter to use; * Parameter 2: string to separate;  Parameter 3: Optional, divide the string up to several, if less than the actual score, then the former n-1 normal points, the last one contains all the remaining strings. * 2.preg_split (): Separates the string with a regular expression, with the same argument, the first parameter is the regular expression * 3.var_dump (Str_split ("Hahah", 2))--->["ha", "Ha", "H"] * */Var_ Dump (Explode (",", "S,t,y,u", 3));  Var_dump (Preg_split ("/[\s,]+/", "Asdh ADCJK, Asjdi")); Var_dump (Str_split ("Hahah", 2));  Var_dump (Mb_split ("/[\w]{1}+/", "sdsd,t,h"));//Bad make/* * 3.implode (): Converts the value of a one-dimensional array to a String * 4.SUBSTR (): truncated string; * First parameter: The string to be intercepted; * The second argument: from which character to start interception; * Third argument: length of string to intercept (default intercept to last) * 5.MB_SUBSTR ():Used to intercept Chinese strings, a Chinese character = 1 characters; * (important) strstr (): Alias STRCHR (): Find and return a string, whether it contains a substring, if not found returns false * Parameter 1: the string to be searched, required; * Parameter 2: required; * Parameter 3:true/false: Returns the previous part of the substring; returns all strings of substrings and substrings, default; * 6.STRISTR (): function as above, case insensitive, * 7.STRRCHR (): Takes the position where the last occurrence of the character is to be found in the string; * First parameter:  The string to be searched for; * Second argument: The character to be looked up, if the second argument is a string, the first character of the string is used, and if found, returns the last occurrence of the string, the next part.  * */Var_dump (Implode ("-", ["a", "B", "C"]));//---> "a-b-c";  Var_dump (substr ("12345", 2,3));  Var_dump (mb_substr ("1234 haha", 2,4));  Var_dump ("1234", "Strstr", "true"); Var_dump (STRISTR ("123 haha 4", "Ha", true)); Var_dump (STRRCHR ("abc123abc456", "ADBC")); /* "String Lookup" * 1.strpos (): Returns a String that finds the first occurrence of a string; * Parameter 1: the string to be searched; * Parameter 2: substring to be found; * Parameter 3: Search from first position; * 2.strrpos (): Return Returns a string that finds the last occurrence of the string, * 3.stripos (): Case insensitive. Returns the position of the first occurrence; * 4.STRRIPOS (): Case insensitive. Returns the last occurrence of the position, * */Var_dump (Strpos ("123AxhBzABC", "abc", 1)),//8 Var_dump (Strripos ("123AxhBzABC", "abc")),//8 Var_dump ( Strrpos ("123AxhBzABC", "abc", 1));//8 Var_dump (Stripos ("123AxhBzABC", "abc", 1));//8/* "String substitution" * str_replace ():Replaces the specified part of the string with the specified content; * Parameter 1: The replaced part, which can be an array or a string; * Parameter 2: New content, either an array or a string; * Parameter 3: the original string; * divided into three categories: 1. The first string, the second string; 2. The first array, the second array: replace the two arrays with each other; *① two arrays are equal in length; *② the first array > second array: The rest of the first array is replaced with "" (that is, deleted); *③ First array < second  Array: The remainder of the second array is not used; * 3. The first array, the second string: Each of the arrays is replaced with a string; * */Var_dump (Str_replace ("E", ",", "Jasbdheead");  Var_dump (Str_replace (["E", "a", "D"], ",", "Jasbdheead"));  Var_dump (Str_replace (["E", "a", "D"],[",", "/", ""], "jasbdheead"));  Var_dump (Str_replace (["E", "a", "D"],[",", "/"], "jasbdheead"));  Var_dump (Str_replace (["E", "a"],[",", "/", "-"], "jasbdheead")); Var_dump (Str_replace (["E", "a", "D"], "/", "Jasbdheead"));

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.