1. Merge arrays
Thearray_merge() function merges arrays together and returns a combined array. The resulting array starts with the first input array parameter, and is added sequentially in the order in which subsequent array parameters appear. Its form is:
- array array_merge (array array1 array2…,arrayN)
This function combines the cells of one or more arrays, and the values in one array are appended to the previous array. Returns the resulting array.
If the input array has the same string key name, the value after the key name will overwrite the previous value. However, if the array contains numeric keys, the subsequent values will not overwrite the original values but will be appended to them.
If only an array is given and the array is numerically indexed, the key names are re-indexed in a consecutive manner.
- $fruits = array("apple","banana","pear");
- $numbered = array("1","2","3");
- $cards = array_merge($fruits, $numbered);
- print_r($cards);
- // output
- //Array ([0] => apple [1] => banana [2] => pear [3] => 1 [4] => 2 [5] => 3 )
- ?>
2. Append array
The array_merge_recursive() function is the same as array_merge(). It can merge two or more arrays together to form a combined array. The difference between the two is that the function will handle it differently when a key in an input array already exists in the result array. array_merge() will overwrite the previously existing key/value pairs and replace them with the key/value pairs in the current input array, while array_merge_recursive() will merge the two values together to form a new array with the original keys. as an array name. There is also a form of array merging, which is to recursively append arrays. Its form is:
- array array_merge_recursive(array array1,array array2[…,array arrayN])
Program examples are as follows:
- $fruit1 = array("apple" => "red", "banana" => "yellow");
- $fruit2 = array("pear" => "yellow", "apple" => "green");
- $result = array_merge_recursive($fruit1, $fruit2);
- print_r($result);
- // output
- // Array ( [apple] => Array ( [0] => red [1] => green ) [banana] => yellow [pear] => yellow )
- ?>
Now the key apple points to an array consisting of two indexed arrays of color values.
3. Connect arrays
Thearray_combine() function will get a new array, which consists of a set of submitted keys and corresponding values. Its form is:
- array array_combine(array keys,array values)
Note that the two input arrays must be the same size and cannot be empty. Examples are as follows
- $name = array("apple", "banana", "orange");
- $color = array("red", "yellow", "orange");
- $fruit = array_combine($name, $color);
- print_r($fruit);
- // output
- // Array ( [apple] => red [banana] => yellow [orange] => orange )
- ?>
4. Split array array_slice()
Thearray_slice() function will return a part of the array, starting from the key offset and ending at offset+length. Its form:
- array array_slice (array array, int offset[,int length])
When offset is a positive value, splitting will start from the offset position from the beginning of the array; if offset is a negative value, splitting will start from the offset position from the end of the array. If the optional length parameter is omitted, the split will start at offset and go to the last element of the array. If length is given and is positive, it ends at offset+length from the beginning of the array. Conversely, if length is given and is negative, it ends at count(input_array)-|length| from the beginning of the array. Consider an example:
- $fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");
- $subset = array_slice($fruits, 3);
- print_r($subset);
- // output
- // Array ( [0] => Pear [1] => Grape [2] => Lemon [3] => Watermelon )
- ?>
然后我们使用下负长度:
- $fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");
- $subset = array_slice($fruits, 2, -2);
- print_r($subset);
- // output
- // Array ( [0] => Orange [1] => Pear [2] => Grape )
- ?>
5. 接合数组 array_splice()
array_splice()函数会删除数组中从offset开始到offset+length 结束的所有元素,并以数组的形式返回所删除的元素。其形式为:
- array array_splice ( array array , int offset[,length[,array replacement]])
offset 为正值时,则接合将从距数组开头的offset 位置开始,offset 为负值时,接合将从距数组末尾的offset 位置开始。如果忽略可选的length 参数,则从offset 位置开始到数组结束之间的所有元素都将被删除。如果给出了length 且为正值,则接合将在距数组开头的offset + leng th 位置结束。相反,如果给出了length且为负值,则结合将在距数组开头的count(input_array)-length的位置结束。实例如下:
- $fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");
- $subset = array_splice($fruits, 4);
- print_r($fruits);
- print_r($subset);
- // output
- // Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Pear )
- // Array ( [0] => Grape [1] => Lemon [2] => Watermelon )
- ?>
You can use the optional parameter replacement to specify the array to replace the target part. Examples are as follows:
- $fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");
- $subset = array_splice($fruits, 2, -1, array("Green Apple", "Red Apple"));
- print_r($fruits);
- print_r($subset);
- // output
- // Array ( [0] => Apple [1] => Banana [2] => Green Apple [3] => Red Apple [4] => Watermelon )
- //Array ([0] => Orange [1] => Pear [2] => Grape [3] => Lemon )
- ?>
You can clearly see how to use this function from the program.
6. Intersection of arrays array_intersect()
The
array_intersect() function returns a key-preserved array consisting only of values that appear in the first array and appear in every other input array. Its form is as follows:
- array array_intersect(array array1,array array2[,arrayN…])
The following example will return all fruits that appear in the $fruit1 array and also appear in $fruit2 and $fruit3:
- $fruit1 = array("Apple","Banana","Orange");
- $fruit2 = array("Pear","Apple","Grape");
- $fruit3 = array("Watermelon","Orange","Apple");
- $intersection = array_intersect($fruit1, $fruit2, $fruit3);
- print_r($intersection);
- // output
- // Array ( [0] => Apple )
- ?>
The array_intersect() function will consider two elements to be the same only if they are equal and have the same data type.
7. Intersection of associative arrays array_intersect_assoc()
The function array_intersect_assoc() is basically the same as array_intersect(), except that it also considers the keys of the array in the comparison. Therefore, only key/value pairs that appear in the first array and also appear in all other input arrays are returned in the result array.
The form is as follows:
- array array_intersect_assoc(array array1,array array2[,arrayN…])
The following example returns all key/value pairs that appear in the $fruit1 array and also appear in $fruit2 and $fruit3:
- $fruit1 = array("red"=>"Apple","yellow"=>"Banana","orange"=>"Orange");
- $fruit2 = array("yellow"=>"Pear","red"=>"Apple","purple"=>"Grape");
- $fruit3 = array("green"=>"Watermelon","orange"=>"Orange","red"=>"Apple");
- $intersection = array_intersect_assoc($fruit1, $fruit2, $fruit3);
- print_r($intersection);
- // output
- //Array ( [red] => Apple )
- ?>
8. Difference of array array_diff()
Function array_diff() returns values that appear in the first array but not in other input arrays. This function is the opposite of array_intersect().
- array array_diff(array array1,array array2[,arrayN…])
Examples are as follows:
- $fruit1 = array("Apple","Banana","Orange");
- $fruit2 = array("Pear","Apple","Grape");
- $fruit3 = array("Watermelon","Orange","Apple");
- $intersection = array_diff($fruit1, $fruit2, $fruit3);
- print_r($intersection);
- // output
- // Array ( [1] => Banana )
- ?>
9. Difference of associative array array_diff_assoc()
The function array_diff_assoc() is basically the same as array_diff(), except that it also takes into account the keys of the array when comparing. Therefore, only key/value pairs that appear in the first array but not in the other input arrays are returned in the result array. Its form is as follows:
- array array_diff_assoc(array array1,array array2[,arrayN…])
The following example only returns [yellow] => Banana, because this special key/value pair appears in $fruit1, but does not exist in $fruit2 and $fruit3.
- $fruit1 = array("red"=>"Apple","yellow"=>"Banana","orange"=>"Orange");
- $fruit2 = array("yellow"=>"Pear","red"=>"Apple","purple"=>"Grape");
- $fruit3 = array("green"=>"Watermelon","orange"=>"Orange","red"=>"Apple");
- $intersection = array_diff_assoc($fruit1, $fruit2, $fruit3);
- print_r($intersection);
- // output
- //Array ( [yellow] => Banana )
- ?>
When using an array, you often need to traverse the array. Often you need to iterate through an array and get the individual keys or values (or get both keys and values), so not surprisingly, PHP provides some functions for this purpose. Many functions perform two tasks, not only obtain the key or value at the current pointer position, but also move the pointer to the next appropriate position.
10. Get the current array key key()
Thekey() function returns the key at the current pointer position in input_array. Its form is as follows:
- mixed key(arrayarray)
The following example outputs the keys of the $fruits array by iterating over the array and moving the pointer:
- $fruits = array("apple"=>"red", "banana"=>"yellow");
- while ($key = key($fruits)) {
- printf("%s
", $key); - next($fruits);
- }
- // apple
- // banana
Note that the pointer will not be moved each time key() is called. To do this, you need to use the next() function. The only function of this function is to complete the task of advancing the pointer.
11. Get the current array value current()
The current() function returns the array value at the current pointer position in the array. Its form is as follows:
- mixed current(arrayarray)
Let’s modify the previous example. This time we want to get the array value:
- $fruits = array("apple"=>"red", "banana"=>"yellow");
- while ($fruit = current($fruits)) {
- printf("%s
", $fruit); - next($fruits);
- }
- // red
- //yellow
12. Get the current array key and value each()
The
each() function returns the current key/value pair of input_array and advances the pointer one position. Its form is as follows:
- array each(array array)
The returned array contains four keys, key 0 and key contain the key name, and key 1 and value contain the corresponding data. If the pointer is at the end of the array before each() is executed, false is returned.
- $fruits = array("apple", "banana", "orange", "pear");
- print_r (each($fruits));
- //Array ([1] => apple [value] => apple [0] => 0 [key] => 0 )
each() is often used in conjunction with list() to iterate over an array. This example is similar to the previous example, but the entire array is output in a loop:
- $fruits = array("apple", "banana", "orange", "pear");
- reset($fruits);
- while (list($key, $val) = each($fruits))
- ~ }
- // 0 => apple
- // 1 => banana
- // 2 => orange
- // 3 => pear
- Because assigning one array to another array will reset the original array pointer, in the above example if we assign $fruits to another variable inside the loop, it will cause an infinite loop. This completes array traversal.
Finding, filtering and searching array elements are some common functions of array operations. Here are some related functions.
13. in_array() function
The
in_array() function searches for a specific value in an array and returns true if the value is found, otherwise it returns false. Its form is as follows:Php code
- Look at the following example to find whether the variable apple is already in the array. If it is, output a piece of information:
- $fruits = array("apple","banana","orange", "pear");
- if( in_array($fruit,$fruits) )
- echo "$fruit is already in the array";
- The third parameter is optional, it forces in_array() to consider the type when searching.
14. array_key_exists() function
If a specified key is found in an array, the function array_key_exists() returns true, otherwise it returns false. Its form is as follows:
Php code
- The following example will search for apple in the array key, and if found, will output the color of this fruit:
- $fruit["apple"] = "red";
- $fruit["banana"] = "yellow";
- $fruit["pear"] = "green";
- if(array_key_exists("apple", $fruit)){
- printf("apple's color is %s",$fruit["apple"]);
- }
- //apple's color is red