PHP common array functions and examples

Keywords: PHP

1, Some basic operation functions of array about key name and value
1. Get all keys or values of the array: array_keys() array_values()

$arr_keys = array_keys($array);$arr_values = array_values($arr);

2. Exchange the positions of keys and values in the array. If the previous one is repeated, it will be overwritten by the following one: array_flip()

$arr2 = array_flip($arr);

3. Whether the given value is in the array: in_array(value,array)

$bool = in_array('hello',$arr);

4. Search for a value in the array, return its key if it is not, and return false: array if it is not_ search()

$bool = array_search('hello',$arr);

5. Whether the given key exists in the array: isset(array[key]) and array_key_exists(key,array)

$bool = array_key_exists('a',$arr);

6. Get the number of array elements: count(array,mode). When mode is 1, it means to count the array recursively. The default is 0. Alias sizeof()

$n = count($arr);  //Equivalent to: $n = sizeof($arr);

7. Change the key names in the array to all lowercase or uppercase: array_change_key_case(array,case). Case has two common quantities: CASE_UPPER or case_ Lower (default), which is all lowercase by default

$lowarr = array_change_key_case($arr,CASE_LOWER);

8. Count the number of occurrences of all values in the array: array_count_value(array). Returns an array. The key is the value of the original array. The value is the number of times this element appears in the original array

$arr_count = array_count_values($arr);

9. Get the first or last key name of the array: array_key_first(array),array_key_last(array)

$key = array_key_first($arr)

10. Pop up the last element of the array:

$last = array_pop($array);

Press one or more cells into the end of the array or the beginning of the array, and return the number of new arrays:

$new_array = array_push($array,$value1,$value2,...);$new_array = array_unshift($array,$value1,$value2,...);

11. Reverse the array: array_reverse(array)

$reverse = array_reverse($arr)

12. Sum or product all values in the array:

$sum = array_sum($array);$product = array_product($array);

13. Remove duplicate values from the array:

array_unique($array,,SORT_STRING);sort_falgs Parameters are used to modify sorting behavior: SORT_NUMERIC - Compare in numerical form SORT_STRING - Compare in string form

14. Disrupt array: shuffle(array)

$bool = shuffle($arr);

15. Randomly obtain one or more key names from the array: array_rand(array,num=1) returns an array containing random key names.

2, Summary of some operation functions of array creation and segmentation
1. Divide an array into multiple arrays: array_chunk(array,size,preserve_keys)
Parameters:
size: indicates the number of elements in each array
preserve_keys: indicates whether to keep the original key name. The default value is false.
Function returns a two-dimensional array

$myarr = array_chunk($arr,2)

2. Create an array with the value of one array as its key name and the value of another array as its value: array_combine(keys,values)

$arr_1 = ['A','B','C'];$arr_2 = ['a','b','c'];$arr_3 = array_combine($arr_1,$arr_2);

3. Fill the array with the specified key and value: array_fill_keys(keys,value)

$keys = array('foo', 5, 10, 'bar');$a = array_fill_keys($keys, 'banana');

4. Fill the array with the given value: array_fill(start_index,num,value)
Parameters:
start_index: the first index of the array
num: the number of inserted elements, that is, the length of the array, must be non negative
Value: the value to fill in

$arr = array_fill(0,10,'myname');

5. Merge one or more arrays: array_merge(array1,array2...)
If the key names are the same, the character key name will be overwritten, and the number key name will not be overwritten, but appended to the back

$a = array_merge($arr_1,$arr_2);

6. Recursively merge one or more arrays: array_merge_recursive(array_1,array_2,...)
If the array has the same array key name, the latter value will not overwrite the original value, but will be appended to it

7. Fill a value into the array with the specified length: array_pad(array,size,value)
Parameters:
size: the length of the filled array. If it is regular, it will be filled to the right of the array. If it is negative, it will be filled to the left of the array
Value: the value to fill in

8. Take a segment from the array: array_slice(array,offset,length,preserve_keys)
Parameters:
Offset: the starting offset, positive or negative
Length: the obtained length. A positive number indicates the number of obtained elements, and a negative number indicates the distance from the end of the array
preserve_keys: do you want to keep the original key name

10. Remove a part of the array and replace it with other values: array_splice(array,offset,length,replacement_array)
Parameters:
replacement_array: the removed cells are replaced by cells in this array

11. Create an array with variables: compact(var1,var2,...), the variable name is the key name, and the variable value is the value of the element

12. Export variables from the array: extract(array), the key name is the variable name, and the value is the value of the variable

13. Assign the value of the array to the variable: list(var1,var2,...)

list($drink, , $power) = array('coffee', 'brown', 'caffeine');

14. Create an array according to the range, including the specified elements: range(start,end,step)

range(0,8,2) ==> [0,2,4,6,8]

3, The basic array sorting function is called sort
Other extensions can be added: r means reverse sorting, k means sorting key names, a means maintaining index relationship, and u means comparing with user-defined functions. 1. Introduce the sort function in detail. Other functions are similar

/*bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )SORT_REGULAR The parameter can change the sorting behavior with the following values: SORT_REGULAR - normal comparison unit (without changing type) SORT_NUMERIC - cells are compared to sort as numbers_ String - the cell is compared to sort as a string_ LOCALE_ String - compare cells as strings according to the current locale setting, which can be changed with setlocale(). SORT_NATURAL - like natsort(), sorts strings in "natural order" for each cell. New in PHP 5.4.0. SORT_FLAG_CASE - able to work with SORT_STRING OR SORT_NATURAL merge (OR bit operation), sort strings case insensitive. */

Sorting functions are roughly classified as follows:

2.sort(),rsort():Sort values in ascending and descending order 3.ksort(),krsort():Sort key names in ascending and descending order 4.asort(),arsort():While maintaining the index relationship, the values are sorted in ascending and descending order 5.usort(),uksort(),uasort():The user-defined sorting function is used to sort by value, key name and index relationship 6.natsort():Use the natural sorting algorithm to sort the array 7.natcasesort():Use the natural sorting algorithm to sort the array case insensitive

4, Array operation
For the calculation of array difference set, u means using custom callback function, diff means using data as difference set, assoc means using index as difference set

1. Calculate the difference set of the array: array_diff(array1,array2,...) compares array1 with other arrays and returns values in array1 but not in other arrays. Returns an array, but the key name is not reserved

2. Use the callback function to compare data to calculate the difference set of the array: array_udiff(arr1,arr2,...,value_cpmpare_func)
Use user-defined functions for data comparison instead of built-in functions.

3. Use key name comparison to calculate the difference set of the array: array_diff_key(array1,array2,...)
Use key names instead of values for difference set calculations

4. Use the callback function to compare the key names and calculate the difference set of the array: array_diff_ukey(arr1,arr2,...,key_compare_func)

5. Check the difference set of the calculated array with index: array_diff_assoc(array1,array2,..)
Use both key name and value for difference set calculation

6. Check the difference set of the calculated array with the index, and compare the index with the callback function: array_diff_uassoc(arr1,arr2,...,key_compare_func)
key_compare_func: user defined function for comparing key names.

7. Check the difference set of the calculated array with the index, and compare the data with the callback function: array_udiff_assoc(arr1,arr2,...,value_cpmpare_func)
value_cpmpare_func: user defined function for comparing data

8. Use the callback function to compare the data and index, and calculate the difference set of the array: array_udiff_uassoc(arr1,arr2,...,value_cpmpare_func,key_compare_func)

Like the difference set, the calculation of array intersection also has 8 functions:

array_intersect()                     
Use data for intersection comparison array_uintersect()                    
Use data for intersection comparison, but custom function comparison array_intersect_key()                 
Intersection comparison using key names array_intersect_ukey()                
Cross comparison using key names, but custom function comparison array_intersect_assoc()               
Use both data and key names array_intersect_uassoc()              
Use both data and key names, but key names are compared using custom functions
array_uintersect_assoc()              Both data and key names are used, but the data is compared using custom functions
array_uintersect_uassoc()             Both data and key names are used, and custom functions are used

Posted by Anim9or on Fri, 24 Sep 2021 00:56:15 -0700