Basic functions of array manipulation
The key name and value of the array
Array_values ($arr); Get the value of an array
Array_keys ($arr); Gets the key name of the array
Array_flip ($arr); the values in the array are exchanged with the key names (if there are duplicates, the previous one will be overwritten by the following)
In_array ("Apple", $arr); Retrieve Apple in an array
Array_search ("Apple", $arr); Retrieve Apple in an array if there is a return key name
Array_key_exists ("Apple", $arr); Retrieves whether the given key name exists in the array
Isset ($arr [Apple]): Retrieves whether the given key name exists in the array
An internal pointer to an array
Current ($arr); Returns the cell in the array
POS ($arr); Returns the current cell in the array
Key ($arr); Returns the key name of the current cell in the array
Prev ($arr); Rewind the internal pointer in the array back to a
Next ($arr); Move the inner pointer in the array forward one
End ($arr); point the inner pointer in the array to the last cell
Reset ($arr; point the inner pointer in the array to the first cell
Each ($arr), constructs an array that returns a key name/value of the current element of the array, and moves the array pointer forward one
List ($key, $value) =each ($arr); Gets the key name and value of the current element of the array
Conversions between arrays and variables
Extract ($arr); used to convert an element in an array into a variable and import it into the current file, the key name as the variable name, and the value as the variable value
Note: (The second parameter is very important, can see the manual use) method of use echo $a;
Compact (VAR1,VAR2,VAR3); Create an array with the given variable name
Ii. segmentation and padding of arrays
Fragment of an array
Array_slice ($arr, 0, 3); You can take a paragraph out of the array, this function ignores the key name
Array_splice ($arr, 0,3,array ("Black", "maroon")); You can take a paragraph out of an array, unlike the previous function, in which the returned sequence is removed from the original array.
Splitting multiple arrays
Array_chunk ($arr, 3,true); You can split an array into multiple, TRUE to preserve the key name of the original array
Padding of arrays
Array_pad ($arr, 5, ' X '); fills an array into a set length
Three, arrays and stacks
Array_push ($arr, "apple", "pear"), pressing one or more elements into the end of the array stack (into the stack), returning the number of elements in the stack
Array_pop ($arr); pops the last element of the array stack (out of the stack)
Iv. Arrays and queues
Array_shift ($arr); The first element in the array is moved out and returned as a result (array length minus 1, other elements move forward one bit, number key name changed from zero technology, text key name unchanged)
Array_unshift ($arr, "a", array); inserts one or more elements at the beginning of the array
Five, callback function
Array_walk ($arr, ' function ', ' words '); Use the user function to process each member in the array (the third argument is passed to the callback function)
Array_mpa ("function", $arr 1, $arr 2); You can work with multiple arrays (they should be the same length when using two or more arrays)
Array_filter ($arr, "function"), using a callback function to filter each element in the array, if the callback function is true, the current element of the array is included in the returned result array, and the key name of the array remains unchanged
Array_reduce ($arr, "function", "*"), converted to a single-valued function (* The first value of an array)
Vi. Ordering of arrays
Sort by array of element values
Sort ($arr), sorted by order of small to large (the second argument is sorted by what sort), and the array ordering of the key names is ignored
Rsort ($arr); Sort by order of large to small (the second argument is sorted by what sort) ignores the array ordering of the key names
Usort ($arr, "function"); Sorts the values in the array using a user-defined comparison function (two parameters in function, 0 for equality, positive for the first one greater than the second, negative for the first less than the second) to sort the array with the key name omitted
Asort ($arr); Sort by the order of small to large (the second argument is sorted by what way) the array of reserved key names
Arsort ($arr); Sort by order of large to small (the second parameter is sorted by what sort) the array of reserved key names
Uasort ($arr, "function"); Sorts the values in the array using a user-defined comparison function (two parameters in function, 0 for equality, positive for the first one greater than the second, negative for the first one less than the second) to sort the array of reserved key names
Sort arrays by key names
Ksort ($arr); Order by Key Name
Krsort ($arr); reverse order by Key name
Uksort ($arr, "function"); Use a user-defined comparison function to sort the key names in the array (there are two parameters in function, 0 for equality, positive for the first greater than the second, and negative for the first one less than the second one)
Sort by natural sort
Natsort ($arr); natural sort (Ignore key name)
Natcasesort ($arr); natural sort (ignoring case, ignoring key name)
Vii. Calculation of arrays
Sum of array elements
Array_sum ($arr); sums all elements inside an array
Merging of arrays
Array_merge ($arr 1, $arr 2); merges two or more arrays (the same string key name, followed by overwriting the previous, same numeric key name, followed by no overwrite operation, but appended to the back)
"+" $arr 1+ $arr 2; For the same key name only the latter one is retained
Array_merge_recursive ($arr 1, $arr 2); Recursive merge operations, if the array has the same string key name, these values will be merged into an array. If a value is itself an array, it will be merged into another array according to the corresponding key name. When the array has the same array key name, the latter value will not overwrite the original value, but append to the back
The difference set of an array
Array_diff ($arr 1, $arr 2); Returns an array of difference results
ARRAY_DIFF_ASSOC ($arr 1, $arr 2, $arr 3); Returns the array of difference results, and the key names are also compared
Intersection of arrays
Array_intersect ($arr 1, $arr 2); Returns an array of intersection results
ARRAY_INTERSECT_ASSOC ($arr 1, $arr 2); Returns an array of intersection results, and the key names are also compared
Eight, other array functions
Range (0,12); Create an array containing the specified range of cells
Array_unique ($arr); Removes duplicate values from the array, preserving the original key names in the new arrays
Array_reverse ($arr, TRUE); Returns an array whose cell order is the opposite of the original array, if the second argument is TRUE to preserve the original key name
Srand (float) microtime () *10000000); Random seed Trigger
Array_rand ($arr, 2); Randomly remove one or more elements from an array
Shuffle ($arr); disturb the order of the array
This class of functions allows you to manipulate arrays and interact with them in a variety of ways. The essence of an array is to store, manage, and manipulate a set of variables.
PHP supports one-dimensional and multidimensional arrays that can be created by the user or created by another function. There are certain database processing functions that can generate arrays from database queries, and some functions return arrays.
array_change_key_case-returns an array of string key names that are all lowercase or uppercase
array_chunk-splits an array into multiple
Array_combine-creates an array with the value of an array as its key name, and the value of another array as its value
array_count_values-the number of occurrences of all values in the statistics array
array_diff_assoc-with index Check the difference set of the computed array
array_diff_key-Calculating the difference set of an array using the key name comparison
array_diff_uassoc-uses the user-supplied callback function to do an index check to calculate the difference set of the array
array_diff_ukey-using a callback function to compare the difference set of an array to a key name
array_diff-Calculating the difference set of an array
Array_fill_keys-fill an array with values, specifying keys
array_fill-fills an array with the given value
array_filter-filter cells in an array with callback functions
Array_flip-exchanging keys and values in an array
array_intersect_assoc-with index Check the intersection of computed arrays
array_intersect_key-calculating the intersection of an array using the key name comparison
array_intersect_uassoc-with index Check the intersection of computed arrays, using callback function to compare indexes
Array_intersect_ukey-computes the intersection of an array using a callback function to compare the key names
Array_intersect-computes the intersection of an array
array_key_exists-checks whether the given key name or index exists in the array
array_keys-returns all the key names in the array
Array_map-the callback function to the cell of the given array
array_merge_recursive-to merge one or more arrays recursively
array_merge-merging one or more arrays
array_multisort-to sort multiple arrays or multidimensional arrays
Array_pad-fills an array to a specified length with a value
array_pop-pops the last cell of the array (out of the stack)
Array_product-computes the product of all values in an array
array_push-pressing one or more cells into the end of the array (into the stack)
array_rand-random extraction of one or more cells from an array
array_reduce-iteratively to simplify the array to a single value with a callback function
array_reverse-returns an array of cells in reverse order
array_search-searches for the given value in the array, and returns the corresponding key name if successful
Array_shift-moves the cell at the beginning of the array to a group
array_slice-remove a paragraph from an array
array_splice-remove part of the array and replace it with other values
Array_sum-computes the and of all values in the array
array_udiff_assoc-with index Check the difference set of the computed array, using the callback function to compare the data
array_udiff_uassoc-with index Check to calculate the difference of the array, compare the data and index with the callback function
array_udiff-comparing data with callback functions to calculate the difference set of an array
array_uintersect_assoc-with index Check the intersection of the computed array, using the callback function to compare the data
array_uintersect_uassoc-with index Check the intersection of computed arrays, using callback functions to compare data and indexes
Array_uintersect-computes the intersection of an array, compares the data with a callback function
array_unique-duplicate values in an array
array_unshift-inserting one or more cells at the beginning of an array
array_values-returns all values in the array
array_walk_recursive-applying user functions recursively to each member in an array
array_walk-applying user functions to each member in an array
array-creating a new array
arsort-an array in reverse order and maintain an index relationship
asort-sorting an array and maintaining an index relationship
compact-create an array, including the variable names and their values
count-count the number of cells in an array or the number of properties in an object
current-returns the current cell in the array
each-returns the current key/value pair in the array and moves the array pointer forward one step
end-the inner pointer of an array to the last cell
extract-importing variables from an array into the current symbol table
in_array-checks if a value exists in the array
key-getting the key name from the associative array
krsort-an array in reverse order by key name
ksort-sorting arrays by key name
List-assigns the values in the array to some variables
natcasesort-sorting of case-insensitive letters using the "natural sort" algorithm for arrays
natsort-using the "natural sort" algorithm to sort arrays
next-moves the inner pointer in the array forward one
Alias for Pos-current ()
prev-the internal pointer of the array back to a
range-creating an array containing the specified range of cells
reset-the inner pointer of an array to the first cell
rsort-reverse sequence of an array
shuffle-Array is scrambled
Alias for Sizeof-count ()
sort-sorting an array of arrays
uasort-use a user-defined comparison function to sort the values in the array and keep the index associated
uksort-using a user-defined comparison function to sort the key names in an array
usort-using a user-defined comparison function to sort values in an array
Working with arrays
In the previous chapters, the variables we introduced are scalar variables that store only a single data. An array is a variable that can store a set or series of values. An array can have a number of elements. Each element has a value, such as text, a number, or another array. An array containing other arrays is called a multidimensional array.
3.1 What is an array
A scalar variable is a named range that is used to store numeric values. Similarly, an array is a named range used to store a series of variable values, so you can use arrays to organize scalar variables.
The values stored in the array are called array elements. Each array element has an associated index (also called a keyword) that can be used to access the element. In most programming languages, arrays have numeric indexes, and these are usually started from 0 or 1.
3.2 Numeric Index array
In PHP, the default value for a numeric index starts at 0, and of course it can be changed.
3.2.1 Initialization of a numeric index array
$porducts = Array (' Tires ', ' oil ', ' Spark plugs ');
Just like the Echo statement, array () is actually a language structure, not a function.
Depending on the requirements of the array contents, it may not be necessary to manually initialize them as in the example above. If the desired data is stored in another array, you can simply copy the array to another array using the operator "=".
If you need to keep the numbers in ascending order in an array, you can use the range () function to create the array automatically. The following line of code will create an array of numbers from 1 to 10: $numbers = range (1,10);
The range () function has an optional third parameter, which allows you to set the steps between values. For example, if you want to create an odd array between 1 and 10, you can use the following code: $ODDS = Range (1,10,2);
The range () function can also manipulate characters, such as: $letters = Range (' A ', ' Z ');
3.2.2 Accessing the contents of an array
To access the contents of a variable, you can use its name directly. If the variable is an array, you can use a combination of the variable name and keyword or index to access its contents. The keyword or index specifies the variable that we want to access. The index is enclosed in square brackets after the variable name.
In the default case, the 0 element is the first element of the array.
Note that although the string parsing feature of PHP is very powerful and intelligent, it can cause confusion. When you embed arrays or other variables in double-quoted strings, you can place them outside the double quotation marks if they are not interpreted correctly, or find a more complex syntax for "string manipulation and regular expressions" in the 4th chapter.
Just like other variables in PHP, arrays do not need to be pre-initialized or created. They are created automatically the first time they are used.
3.2.3. Using a loop to access an array
Because the array uses an ordered number as the index, it is easy to display the contents of the array using a for loop.
for ($i =0; $i <3; $i + +)
echo "$products [$i]";
Using a simple loop, you can access each element as a very good feature of a numeric index array. You can also use a Foreach loop, which is specifically designed for arrays. Such as:
foreach ($products as $current)
Echo $current. ‘ ‘;
3.3 Arrays using different indexes
PHP also supports related arrays. In the related array, you can associate each variable value with any keyword or index.
3.3.1 Initializing related arrays
The code shown below can create a related array with the product name as the keyword and the price as the value:
$prices = Array (' Tires ' =>100, ' oil ' =>10, ' Spark plugs ' =>4);
The symbol between the keyword and the value is just a greater than sign with the equals sign.
3.3.2 Accessing array elements
Similarly, you can use variable names and keywords to access the contents of an array. For example $prices[' Tires ').
3.3.3 Using Loop statements
Because the index of the associated array is not a number, it is not possible to use a simple counter in the FOR Loop statement to operate on the array. However, you can use the Foreach Loop or the list () and each () structure.
The foreach () loop has a different structure when working with a related array using the Foreach Loop statement. You can use keywords as follows:
foreach ($prices as $key = $value)
echo $key. ' = '. $value. ' <br/> ';
The code shown below will print the contents of the $prices array using the each () structure:
while ($element = each ($prices))
echo $element [' key '];
echo $element [' value '];
echo ' <br/> ';
The each () function returns the current element of the array and the next element as the current element. Because the each () function is called in the while loop, it returns each element in the array sequentially, and when it reaches the end of the array, the loop operation terminates.
In this code, the variable $element is an array. When each () is called, it returns an array with 4 numeric values and 4 indexes that point to the array position. The position key and 0 contain the keywords for the current element, while the position value and 1 contain the values of the current element. Although this is not the same as choosing which method, we have chosen to use a named location instead of a numeric index location.
In addition, there is a more advanced and common way to accomplish the same operation. The function list () can be used to decompose an array into a series of values. The two values returned by the function each () can be separated by the following method: List ($product, $price) = each ($price);
The code above uses each () to remove the current element from the $prices array and return it as an array, and then point to the next element. It also uses the list () to change the array returned from each () to 0, 12 elements to two new amounts named $product and $price.
We can iterate through the entire $prices array and display its contents using a short script such as the following:
while (list ($PRODCT, $pirce) = each ($prices))
echo "$product-$price <br/>";
The output of this code is the same as the output from the previous script, but it is easier to read because list () allows naming the new variable.
One thing to note is that when you use the each () function, the array records the current element. If you want to use the array two times in the same script, you must reset the current element to the beginning of the array using the function reset (). To traverse the prices array again, you can use the following code:
while (list ($product, $price) = each ($prices))
echo "$product-$price <br/>";
3.4 Array Operators
+ union, = = equivalence, = = = identical,! = Not equivalent,<> not equivalent,!== not identical.
The Union operator attempts to add an element from $b to the end of $ A. If the element in $b has the same index as some elements in $ A, they will not be added. That is, the element in $ A will not be overwritten.
3.5 Multi-dimensional arrays
An array is not necessarily a simple list of keywords and values--each location in the array can also hold another array. Using this method, you can create a two-dimensional array. You can think of a two-dimensional array as a matrix, or a network with width and height, or rows and columns.
3.6 Array Sorting
3.6.1 using the sort () function
The sort () function is letter-case-sensitive. All the letters are in front of the lowercase letters. So ' a ' is less than ' Z ', and ' Z ' is less than ' a '.
The second parameter of the function is optional. This optional parameter can be passed Sort_regular (default), Sort_numeric, or sort_string. The ability to specify sort types is useful, for example, when you want to compare strings that may contain numbers 2 and 12. From a mathematical point of view, 2 is less than 12, but as a string, ' 12 ' is less than ' 2 '.
3.6.2 sorting related arrays using the Asort () function and the Ksort () function
The function Asort () is sorted according to the value of each element of the array. The Ksort () function is sorted by keyword rather than by value.
3.6.3 Reverse Sort
The function rsort () sorts a one-dimensional numeric index array in descending order. The function arsort () sorts a one-dimensional correlation array in descending order of the value of each element. The function krsort () pin sorts a one-dimensional array in descending order based on the keyword of the array element.
To access data in a one-dimensional array, you need to use the name of the array and the index of the element, except that an element has two indexes--the two-dimensional array and the one-dimensional array are similar, in addition to the rows and columns.
You can use the dual for loop to achieve the same effect:
for ($row =0; $row <3; $row + +)
for ($column =0; $column <3; $column + +)
echo ' | '. $products [$row] [$column];
echo ' |<br/> ';
If you use this code for a large array, it will be much simpler.
You might prefer to create a column name instead of a number. You can use the following code:
$products = Array (' Code ' = ' TIR ', ' descrīption ' = ' Tires ', ' Price ' =>100), Array (' code ' "= ' oil ', ' Des Crīption ' = ' oil ', ' price ' =>10), array (' Code ' = ' SPK ', ' descrīption ' = ' Spark plugs ', ' Price ' =>4)};
It is much easier to use this array if you want to retrieve a single value. Keep in mind that storing the described content in a column named after its name is easier to remember than saving it in the so-called first column. With descriptive indexes, it is not necessary to remember that an element is stored in the [x][y] position. Using the name of a pair of meaningful rows and columns as an index makes it easy to find the data you need.
Then we can't use a simple for loop to iterate through each column sequentially. You can use the For loop to iterate through an external numeric index array, $products. Each row of the $products array is an array with a descriptive index. Use the each () and list () functions in the while loop to traverse the entire internal array. Therefore, you need a for loop with a while loop embedded in it.
for ($row = 0; $row < 3; $row + +}
while (list ($key, $value) = each ($products [$row])
echo "| $value";
echo ' |<br/> ';
Three-dimensional arrays have high, wide, and deep concepts. If you can easily imagine a two-dimensional array as a table with rows and columns, you can think of a three-dimensional array as a bunch of tables like this. Each element can be referenced by layers, rows, and columns.
Depending on how you create a multidimensional array, you can create four-dimensional, five-, or six-dimensional arrays. In PHP, there is no limit to the number of array dimensions, but it is difficult to imagine an array that is more than three-dimensional. Most of the practical problems logically require only three-dimensional or less-dimensional array structures to be used.
3.7 Sorting of multi-dimensional arrays
It is much more complex to sort an array of more than one dimension, or not to row in alphabetical and numeric order. PHP knows how to compare two numbers or strings, but in a multidimensional array, each element is an array. PHP does not know how to compare two arrays, so you need to create a way to compare them. In most cases, the order of words and numbers is obvious-but for complex objects, there are more problems.
3.7.1 user-defined sorting
The "U" in Usort () stands for "user", because this function requires the passing of a custom-defined comparison function. The versions Uasort () and Uksort () corresponding to Asort and Ksort also require incoming user-defined comparison functions.
Similar to Asort (), Uasort () is used when sorting the values of non-numeric indexed arrays. If the value is a simple number or text, you can use Asort. If the value you want to compare is as complex as an array, you can define a comparison function and then use Uasort ().
Similar to Ksort (), use Uksort () when sorting keywords for non-numeric indexed arrays. If the value is a simple number or text, use Ksort. If the object you want to compare is as complex as an array, you can define a comparison function and then use Uksort ().
3.7.2 Reverse User sequencing
The function sort (), Asort (), and Ksort () each correspond to a reverse sort function with the letter "R". User-defined sorting does not have a reverse variant, but you can reverse-sort a multidimensional array.
3.8 reordering An array
3.8.1 using the Shuffle () function
In earlier versions of PHP, shuffle () required that a random number generator be provided first when calling the Srand () function. Now, this step is no longer needed.
If this function is important to you, you can test it on the server before applying the function in the program.
Since it is not necessary to really reorder the entire array, the same functionality can be achieved using the Array_rand () function.
3.8.2 using the Array_reverse () function
The Array_reverse () function uses an array as a parameter to return an array with the same contents as the parameter array but in reverse order.
Because using the range () function alone creates an ascending sequence, you must use the sort () function or the Array_reverse () function to change the number in the array to descending order. Alternatively, you can use the For loop to create this array in one element at a time. Such as:
$numbers = Array ();
for ($i =10; $i >0; $i--)
Array_push ($numbers, $i);
A For loop can be run in descending order like this. You can set the counter
A For loop can be run in descending order like this. You can set the counter's initial value to a large number, and use the operator "--" at the end of each loop to reduce the counter by 1.
Here we create an empty array, and then use the Array_push () function to add each new element to the end of the array. Note that the function opposite Array_push () is Array_pop (), which is used to delete and return an element at the end of the array.
Alternatively, you can use the Array_reverse () function to reverse-order the array created by the range () function.
Note that the Array_reverse () function returns a modified copy of the original array. If you no longer need the original array, as in this example, you can overwrite the original version with the new copy.
If the data is just a series of integers, you can create the array in reverse order by using 1 as the third optional parameter of the range () function.
3.9 loading an array from a file
Uses the file () function to load an entire file into an array. Each line in the file becomes an element in the array. The count () function is used to count the number of elements in the array.
Explode ("\ t", $orders [$i])
The explode () function splits the incoming string into small chunks. Each tab becomes a breakpoint between two elements. The optional parameter limit for this function can be used to limit the maximum number of blocks that are returned.
You can use many methods to extract numbers from a string. Here, we use the Intval () function. It can convert a string into an integer. This conversion is quite intelligent, it can ignore some parts, such as the label cannot be converted to a number.
3.10 Performing other array operations
3.10.1 Browsing in arrays: each (), current (), reset (), end (), Next (), POS (), and Prev ()
As mentioned earlier, each array has an internal pointer to the current element in the array. This pointer is used indirectly when the function each () is used, but it can also be used and manipulated directly.
If a new array is created, the current pointer is initialized and points to the first element of the array.
Calling next () or each () causes the pointer to move forward one element. Calling each ($array _name) returns the current element before the pointer moves forward one position. The next () function is somewhat different--calling next ($array _name) moves the pointer forward and then returns the new current element.
Call End ($array _name) to move the pointer to the end of the array.
To traverse an array backwards, you can use the end () and Prev () functions. The Prev () function is the opposite of the next () function. It is to move the current pointer back one position and then return the new current element.
3.10.2 apply any function to each element of an array: Array_walk ()
The Array_walk () function requires three parameters. The first is arr, which is the array that needs to be processed. The second is the Func, which is the function that the user customizes and will act on each element in the array. The third parameter, UserData, is optional, and if it is used, it can be passed as a parameter to our own function.
See an example of a pin slightly complex point:
Function my_multiply (& $value, $key, $factor)
$value *= $factor;
Array_walk (& $array, ' my_multiply ', 3);
Here, we define a function called my_multiply () that can be multiplied by the provided multiplication factor to multiply each element in the array.
In addition, there is a need to pay attention to the problem is to pass the 毵 number $value way. In the function definition of my_multiply (), the address character (&) preceding the variable means that $value is passed by reference. Passing by reference allows the function to modify the contents of an array.
3.10.3 Statistics array elements: count (), sizeof (), and Array_count_values ()
The count () function and the sizeof () function have the same purpose and can return the number of array elements. You can get the number of elements in a regular scalar variable, if the array passed to the function is an empty array, or is an array of variables that are not set, the number of returned arrays is 0.
If you call Array_count_values ($array), this function will count the number of times each particular value has occurred in the array $array (this is the set of base numbers for the array). This function will return a related array containing the frequency table. This array contains all the values in the array $array and takes these values as keywords for the related array. The value for each keyword is the number of occurrences of the keyword in the array $array.
3.10.4 converting an array into a scalar quantity: Extract ()
For a non-numeric indexed array with many keyword-value pairs, you can use the function extract () to convert them to a series of scalar variables.
The function of extract () is to create a series of scalar variables with an array whose names must be the names of the keywords in the array, while the values of the variables are the values in the array.
The extract () function has two optional parameters: Extract_type and prefix. The variable extract_type will tell the extract () function How to handle the conflict. Sometimes a variable with the same name as the array keyword may already exist, and the default action of the function is to overwrite the existing variable.
The two most common options are extr_overwrite (default) and Extr_prefix_all. Other options may be used when you know that a particular conflict occurs and you want to skip the keyword or prefix it.
Extract () can extract an element that has a keyword that is a valid variable name, which means that keywords that start with a number or that contain spaces are skipped.
Basic functions of array manipulation