This article mainly introduces how to learn PHP arrays [experience]. For more information, see
PHP has many array functions to facilitate array operations.
Definition:
Each object in the array contains two items: key and value. you can use the query key to obtain the corresponding value. These keys can be numeric or associative keys. There is no real relationship between the value key and the value, they are only the position in the array.
PHP provides many methods to traverse arrays. Association keys or numeric keys cannot be used. they all depend on an array pointer.
Create an array
PHP does not need to specify its size when creating an array. because PHP is a loose language, it does not need to be declared before using an array. Without restrictions, PHP provides formal and informal array declaration methods.
Reference each element of the PHP array, which is indicated by a pair of brackets. There is no size limit on the array, so you only need to create a reference to create an array, for example:
$state[0]= ‘111';$state[1]= ‘222';
If the index value is a numerical index and increases progressively, you can also omit the index value during creation.
$state[] =‘111';$state[] =‘222';
You can use array () to create an array, for example:
$state =array(‘111', ‘222');$state =array(‘one'=>'111', ‘two'=>'222');
Use list () to extract an array, for example:
$state= array(‘one', ‘two', ‘three');list($one,$two, $three) = $state;
The three values in the array are assigned to $ one, $ two, and $ three, which can be output directly.
Fill the array with a predefined value range, for example:
$ Num = range (1, 6); // similar to $ num = array (1, 2, 3, 4, 5, 6); you can select parity: $ num = range (1, 6, 2 );
// $ Num = array (1, 3, 5); optional letters: $ ch = range ("A", "F "); // $ ch = array ("A", "B", "C", "D", "E", "F ");
Output array
The most common method for outputting array content is to iteratively process each array key and output the corresponding value.
The foreach () function can easily traverse an array to obtain each value and key.
The print_r () function can easily output the array content to the screen. The prinf_r () function accepts a variable and sends the content to the standard output. if the result is successful, TRUE is returned. otherwise, FALSE is returned.
Test array
The is_array () function is used to determine whether a specific variable is an array.
The is_array () function determines whether a variable is an array. If yes, TRUE is returned. otherwise, FALSE is returned. Even if an array contains only one value, it is considered an array.
Add and delete array elements
PHP provides some functions for expanding and downgrading arrays, facilitating the simulation of various queue implementations.
Add elements to the array header:
The array_unshift () function adds elements to the array header. All existing numeric keys are modified accordingly to reflect their new positions in the array, but the associated keys are not affected.
$state= array(‘11', ‘22', ‘33');array_unshift($state,‘00');//$state= array(‘00', ‘11', ‘22', ‘33');
Add elements at the end of the array:
The array_push () function adds the value to the end of the array. after a new value is added, the total number of elements in the array is returned. At the same time, this variable is passed to this function as an input parameter, and multiple variables (elements) are pushed to the array in the form:
$state= array(‘1', ‘2');array_push($state,‘3');//$state= array(‘1', ‘2', ‘3');
Delete elements from the array header:
The array_shift () function deletes and returns the first element found in the array. The result is that if the value key is used, all corresponding values are moved down, and the array using the associated key is not affected, in the form:
$state= array(‘1', ‘2');array_shift($state);//$state= array(‘2');
Delete elements from the end of the array:
The array_pop () function deletes and returns the last element of the array, in the form:
$state= array(‘1', ‘2');array_pop($state);//$state= array(‘1');
Locate array elements
Search array:
The in_array () function searches for a specific value in the array. if this value is found, TRUE is returned. otherwise, FALSE is returned. the format is as follows:
$user= array(‘111', ‘222', ‘333');$str= ‘111';if(in_array($str,$user)){echo‘yes';}else{echo ‘no';}
The third parameter, strict, is optional. it forces in_array () to consider the type during search.
Search associated array:
If a specified key is found in an array, the array_key_exists () function returns TRUE; otherwise, FALSE. The format is as follows:
$arr= array('one'=>'1', 'two'=>'2', 'three'=>'3');if(array_key_exists('two',$arr)){echo'yes';}else{echo‘no';}
Search associated array:
The array_search () function searches for a specified value in an array. if it is found, the corresponding value is returned. otherwise, FALSE is returned. the format is as follows:
$arr= array('one'=>'1', 'two'=>'2', 'three'=>'3');if(array_search('1',$arr)){echo'yes';}else{echo‘no';}
Obtain the array key:
The array_key () function returns an array containing all the keys found in the searched array. the format is as follows:
$arr= array('one'=>'1', 'two'=>'2', 'three'=>'3');$keys= array_keys($arr);var_dump($keys);//array(3) {[0]=> string(3) "one" [1]=> string(3) "two" [2]=>string(5) "three" }
Obtain the array value:
The array_values () function returns all values in an array and automatically provides an array index for the returned array. the format is as follows:
$arr= array('one'=>'1', 'two'=>'2', 'three'=>'3');$values= array_values($arr);var_dump($values);//array(3) {[0]=> string(1) "1" [1]=> string(1) "2" [2]=>string(1) "3" }
Traverse arrays
Generally, you need to traverse the array and obtain each key or value (or obtain both the key and value). PHP provides some functions to meet your needs. Many functions can complete two tasks, not only to obtain the key or value of the current pointer position, but also to move the pointer to the next appropriate position.
Get the current array key:
The key () function returns the key where the current pointer is located in the array. the format is as follows:
$arr= array('one'=>'1', 'two'=>'2', 'three'=>'3');$key= key($arr);var_dump($key);//string(3) "one"
Note: the pointer is not moved every time key () is called.
Get the current array value:
The current () function returns the array value of the current pointer position in the array. The format is as follows:
$arr= array('one'=>'1', 'two'=>'2', 'three'=>'3');$value= current($arr);var_dump($value);//string(1)“1”
Get the current array key and value:
The each () function returns the current key/value pair of the array and pushes the pointer to a position in the following format:
$arr =array('one'=>'1', 'two'=>'2', 'three'=>'3');var_dump(each($arr));//array(4) {[1]=> string(1) "1" ["value"]=> string(1)"1" [0]=> string(3) "one" ["key"]=>string(3) "one" }
The returned array contains four keys. Keys 0 and key contain the key name, while Keys 1 and value contain the corresponding data. If the pointer before execution of each () is located at the end of the array, FALSE is returned.
Move the array pointer:
1) move the pointer to the next array location
The next () function returns the array value that is placed next to the current array pointer. if the pointer is originally located at the last position of the array, FALSE is returned.
$ Arr = array ('one' => '1', 'two' => '2', 'Three '=> '3'); echo next ($ arr ); // output 2 echo next ($ arr); // output 3
2) move the pointer to the previous array position
The prev () function returns the array value located at the first position of the current pointer. if the pointer is located at the first position of the array, FALSE is returned.
3) move the pointer to the first array position.
The reset () function is used to set the array pointer back to the starting position of the array. if you need to view or process an array multiple times in the script, this function is often used, in addition, this function is often used at the end of sorting.
4) move the pointer to the last array position.
The end () function moves the pointer to the last position of the array and returns the last element.
Pass the array value to the function:
The array_walk () function transmits each element in the array to the user-defined function. If you need to perform a specific action on each array element, this function will work. The format is as follows:
functiontest($value ,$key){echo$value.' '.$key."";}$arr= array('one'=>'1', 'two'=>'2', 'three'=>'3');array_walk($arr,'test');//1 one//2 two//3 three
If multi-dimensional array is used, the array_walk_recursive () function introduced in PHP5 can recursively apply a user-defined function to each element in the array.
Determine array size and element uniqueness
Determine the size of the array:
The count () function returns the total number of values in the array.
If the optional mode parameter is enabled (set to 1), the array performs recursive counting statistics. Count (array (), 1 );
Note: The sizeof () function is the alias of count. Consistent functions.
Count the frequency of array elements:
The array_count_values () function returns an array containing correlated key/value pairs in the following format:
$arr= array('A', 'B', 'C', 'A');$res= array_count_values($arr);print_r($res);//Array( [A] => 2 [B] => 1 [C] => 1 )
Value indicates the frequency of occurrence.
Determine the unique array element:
The array_unique () function deletes all repeated values in the array and returns an array consisting of unique values. the format is as follows:
$arr= array('A', 'B', 'C', 'A');$res= array_unique($arr);print_r($res);//Array( [0] => A [1] => B [2] => C )
The optional parameter sort_flags (added in PHP5.2.9) determines how to sort the array key. By default, values are sorted as strings, but they can also be sorted by value pairs (SORT_NUMERIC), or by using the default PHP sorting method (SORT_REGULAR ), you can also sort data by the local environment (SORT_LOCALE_STRING ).
Array sorting
Sort array elements in reverse order:
The array_reverse () function resets the order of elements in the array in the following format:
$arr= array('A', 'B', 'C');$res= array_reverse($arr);print_r($res);//Array( [0] => C [1] => B [2] => A )
If the value of the optional parameter preserve_keys is set to TRUE, the key ING is maintained. Otherwise, the values after the placement correspond to the corresponding keys in the previous position.
$arr= array('A', 'B', 'C');$res= array_reverse($arr, true);print_r($res);//Array( [2] => C [1] => B [0] => A )
Replace the array key and value:
The array_flip () function replaces the role of the input key and the corresponding value in the array, as follows:
$arr= array('A', 'B', 'C');$res= array_flip($arr);print_r($res);//Array( [A] => 0 [B] => 1 [C] => 2 )
Array sorting:
The sort () function sorts arrays in the order of values from low to high. The format is as follows:
The sort () function does not return the sorted array. On the contrary, it only sorts the array in "local" and does not return any value regardless of the result. The sort_flags parameter is optional. the default behavior of the function is modified based on the value specified by this parameter.
1) SORT_NUMERIC, sorted by numerical values. It is useful for sorting integers and floating-point numbers.
2) SORT_REGULAR: sorts the elements according to the corresponding ASCII value.
3) SORT_STRING: sorts elements in the correct order close to the human cognition.
The asort () function is required to sort the arrays under the conditions corresponding to the initial key/value.
The assort () function is the same as the sort () function, which sorts the array in ascending order, except that it will maintain the Association of keys and values in the form:
$arr= array('C', 'B', 'A');$res= $arr;print_r($arr);sort($arr);print_r($arr);asort($res);print_r($res);//Array ( [0]=> C [1] => B [2] => A ) Array ( [0] => A [1] => B [2] => C )Array ( [2] => A [1] => B [0] => C )
Sort arrays in reverse order
The rsort () function is the same as the sort () function, except that it sorts array elements in reverse order (in descending order.
If the optional sort_flags parameter is used, the specific sorting behavior is determined by this value.
Sort the array in reverse order with key/value pairs
Like asort (), the arsort () function will maintain a key/value association, but it will reverse the array up
$arr= array('C', 'B', 'A', 'D');arsort($arr);print_r($arr);//Array( [3] => D [0] => C [1] => B [2] => A )
If the optional sort_flags parameter is used, the specific sorting behavior is determined by this value.
Natural sorting of arrays
The natsort () function provides a sorting mechanism that is equivalent to what people usually use.
Typical algorithms are sorted as follows:
P1.jpg, p10.jpg, p2.jpg, p1_jpg
Use the natsort () function as follows:
P1.jpg, p2.jpg, p10.jpg, pw.jpg
Case-insensitive natural sorting
For example:
Picture1.jpg, picture10.jpg, picture2.jpg, and picturew.jpg
Sort array by key value
The ksort () function sorts arrays by pressing the key. if the result is successful, TRUE is returned. if the result is failed, FALSE is returned.
Sort array keys in reverse order
The operation of the krsort () function is the same as that of ksort (), and the operation is also sorted by pressing the key.
Sort by custom rules
The usort () function provides another sorting method. you can use the user-defined comparison algorithm specified in this function to sort arrays. If you want to sort data in some way, and any built-in sorting function in PHP does not provide corresponding support, you need this function.
Array merging, splitting, integration, and decomposition
Merge arrays
The array_merge () function combines arrays and returns a Union array. The obtained array starts with the first input array parameter and is appended in the order in which the following array parameters appear. The format is as follows:
$arr= array('C', 'B', 'A', 'D');$arr1= array('1', '2', '3', '4');$arr2= array_merge($arr, $arr1);print_r($arr2);//Array( [0] => C [1] => B [2] => A [3] => D [4] => 1 [5] => 2 [6]=> 3 [7] => 4 )
Recursive append array
The array_merge_recursive () function is the same as the array_merge () function. you can combine two or more numbers to form a combined array. The difference between the two is that when a key in an input array already exists in the result array, the function will take different processing methods. Array_merge () overwrites the previous key/value pair and replaces it with the key/value pair in the current input array. array_merge_recursive () merges the two values, form a new array and use the original key as the array name. The format is:
$arr= array('one'=>'C', 'one'=>'B');$arr1= array('three'=>'1', 'one'=>'2');$arr2= array_merge_recursive($arr, $arr1);print_r($arr2);//Array( [one] => Array ( [0] => B [1] => 2 ) [three] => 1 )
Merge two arrays
The array_combine () function generates a new array consisting of a group of submitted keys and corresponding values, in the form:
$arr= array('A', 'B');$arr1= array('1', '2');$arr2= array_combine($arr, $arr1);print_r($arr2);//Array( [A] => 1 [B] => 2 )
Split an array
The array_slice () function returns a part of the array, starting from the key offset and ending at the offset + length position.
When offset is a positive value, the split starts from the offset position starting from the array. if offset is a negative value, the split starts from the offset position at the end of the array. If the optional length parameter is omitted, the split starts from offset to the last element of the array. If length is given and it is a positive number, it will end at the offset + length position starting with the array. Conversely, if length is given and it is a negative number, it ends at the count (array)-| length | position starting with the array. The format is as follows:
$arr= array('A', 'B', 'C', 'D');$arr1= array_slice($arr, 2, 1);print_r($arr1);//Array( [0] => C )
Returns the intersection of arrays.
The array_intersect () function returns an array with keys retained. this array is composed of only values that appear in the first array and appear in each other input array. The format is as follows:
$arr= array('A', 'B', 'C', 'D');$arr1= array('A', 'B', 'E');$arr2= array('A', 'F', 'D');$arr3= array_intersect($arr, $arr1, $arr2);print_r($arr3);//Array( [0] => A )
Note: array_intersect () is considered equal only when two elements have the same data type.
Returns the intersection of correlated arrays.
Array_intersect_assoc () is basically the same as array_intersect (), except that the array key is also considered in comparison. Therefore, only key/value pairs that appear in the first array and also appear in all other input arrays are returned to the result array. The format is as follows:
$arr= array('a'=>'A', 'b'=>'B', 'c'=>'C', 'd'=>'D');$arr1= array('a'=>'A', 'c'=>'B', 'E');$arr2= array('a'=>'A', 'b'=>'F', 'd'=>'B');$arr3= array_intersect_assoc($arr, $arr1, $arr2);print_r($arr3);//Array( [a] => A )
Evaluate the difference set of the correlated array
The array_diff_assoc () function is basically the same as the array_diff () function, but the array key is also considered during Comparison. therefore, only key/value pairs that appear in the first array but not in other input arrays will be returned to the result array. The format is as follows:
$arr= array('a'=>'A', 'b'=>'B', 'c'=>'C', 'd'=>'D');$arr1= array('a'=>'A', 'b'=>'B', 'e'=>'E');$arr3= array_diff_assoc($arr, $arr1);print_r($arr3);//Array( [c] => C [d] => D )
Other useful array functions
Returns a random set of keys.
The array_rand () function returns one or more keys in the array. The format is:
$arr= array('a'=>'A', 'b'=>'B', 'c'=>'C', 'd'=>'D');$arr1= array_rand($arr, 2);print_r($arr1);//Array( [0] => b [1] => d )
Randomly shuffled array elements
The shuffle () function randomly sorts array elements.
Summation of values in the array
The array_sum () function adds all values in the array and returns the final sum. The form is as follows:
$arr= array('A', 32, 12, 'B');$count= array_sum($arr);print_r($count);//44
If the array contains other data types (such as strings), these values are ignored.
Divide an array
The array_chunk () function breaks down an array into a multi-dimensional array consisting of multiple arrays containing size elements. The format is as follows:
$arr= array('A', 'B', 'C', 'D');$arr1= array_chunk($arr, 2);print_r($arr1);//Array( [0] => Array ( [0] => A [1] => B ) [1] => Array ( [0] => C [1]=> D ) )