Home >Backend Development >PHP Tutorial >Understanding of several array functions in PHP
2. array_chunk function (PHP 4 >= 4.2.0, PHP 5) array_chunk — split an array into multiple illustrate array array_chunk ( array$input , int$size [, bool$preserve_keys ] ) array_chunk() splits an array into multiple arrays, where the number of cells in each array is determined by size (that is, each array has size elements). The last array may have a few fewer elements. The resulting array is a cell in a multidimensional array, with indexes starting from zero. Set the optional parameter preserve_keys to TRUE to enable PHP to retain the original key names in the input array. If you specify FALSE, each result array will be indexed with a new number starting from zero. The default value is FALSE. This function is relatively easy to understand, so I won’t say much about it. 3. array_flip function (PHP 4, PHP 5) array_flip — swap keys and values in an array illustrate array array_flip (array$trans) array_flip() returns a reversed array, for example, the key names in trans become values, and the values in trans become key names. Note that the value in trans needs to be a legal key name, for example, it needs to be integer or string. A warning will be emitted if the value is of the wrong type, and the key/value pair in question will not be reversed. If the same value appears multiple times, the last key name will be used as its value, and all others are lost. array_flip() returns FALSE if it fails. Note: Call it twice in a row to remove duplicates! 4. array_filter function (PHP 4 >= 4.0.6, PHP 5) array_filter — Filter elements in an array using a callback function illustrate array array_filter ( array$input [, callback$callback ] ) array_filter() passes each value in the input array to the callback function in turn. If the callback function returns TRUE, the current value of the input array will be included in the returned result array. The key names of the array remain unchanged. array_filter() example
Output: Odd : Array ( [a] => 1 [c] => 3 [e] => 5 ) Even: Array ( [0] => 6 [2] => 8 [4] => 10 [6] => 12 ) Users should not modify the array itself in the callback function. For example, add/delete cells or unset the array being acted upon by array_filter(). The behavior of this function is undefined if the array changes. If no callback function is provided, array_filter() will delete all entries in input whose value is FALSE. See Converting to Boolean for more information.
The above example output: Array ( [0] => foo [2] => -1 ) |