Home > Backend Development > PHP Tutorial > PHP array manipulation (merge, split, append, search, delete, etc.)

PHP array manipulation (merge, split, append, search, delete, etc.)

高洛峰
Release: 2023-03-02 15:42:02
Original
1194 people have browsed it

1. Merge arrays
array_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:
Copy code The code is as follows:
array array_merge (array array1 array2...,arrayN)

This function merges the cells of one or more arrays, and the values ​​in one array are appended to the previous array. Returns the resulting array.
If there is the same string key name in the input array, 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 will be re-indexed in a consecutive manner.
Copy the code The code is as follows:
$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
array_merge_recursive() function is the same as array_merge(), and can merge two or more arrays Merge 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:

Copy code The code is as follows:
array array_merge_recursive(array array1,array array2[…,array arrayN])

The program example is as follows:
Copy code The code is 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, which is an indexed array consisting of two color values.
3. Connect arrays
array_combine() function will get a new array, which consists of a set of submitted keys and corresponding values. Its form is:
Copy code The code is as follows:
array array_combine(array keys, array values)

Note that the two input arrays must be the same size and cannot be empty. The example is as follows
Copy the code The code is 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 the array array_slice()
array_slice() function will return a part of the array, starting from the key offset and ending at the offset+length position. Its form:

Copy code The code is as follows:
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 , then splitting starts 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:
Copy code The code is as follows:
$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 )
?>

Then we use the negative length:
Copy code The code is as follows:
$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. Join array array_splice() The
array_splice() function will delete all elements starting from offset and ending at offset+length in the array, and return the deleted elements in the form of an array. Its form is:
Copy code The code is as follows:
array array_splice (array array, int offset[,length[,array replacement]])

When offset is a positive value, the join will start from the offset position from the beginning of the array, offset When negative, the join will start at offset from the end of the array. If the optional length parameter is omitted, all elements starting at offset position and ending at the end of the array will be removed. If length is given and is positive, the join ends at offset + leng th from the beginning of the array. Conversely, if length is given and is negative, the union will end count(input_array)-length from the beginning of the array. The example is as follows:
Copy the code The code is as follows:
$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 )
?>

can be used optional The replacement parameter specifies the array to replace the target part. The example is as follows:
Copy the code The code is 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()
array_intersect() function returns an array with retained keys. This array consists only of values ​​that appear in the first array and appear in every other input array. Its form is as follows:

Copy code The code is as follows:
array array_intersect(array array1,array array2[,arrayN...])

The following example will return the items that appear in the $fruit1 array and also appear in $fruit2 and $fruit3 All fruits:
Copy code The code is as follows:
$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 )
?>

Only when two elements are equal and have the same data type, the array_intersect() function will consider them to be the same.

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:

Copy code The code is as follows:
array array_intersect_assoc(array array1,array array2[,arrayN...])

The following example returns what appears in the $fruit1 array and also appears in $fruit2 and $fruit3 All key/value pairs:
Copy code The code is as follows:
$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 arrays Set array_diff()
The 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().
Copy code The code is as follows:
array array_diff(array array1,array array2[,arrayN...])

The example is as follows:
Copy code The code is 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 array_diff_assoc() of associative arrays

The function array_diff_assoc() is basically the same as array_diff() except that it also considers 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:
Copy code The code 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, it does not exist in $fruit2 or $fruit3.
Copy the code The code is as follows:
$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, it is often necessary to traverse the array. It is often necessary 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()
key() function returns the key at the current pointer position in input_array. Its form is as follows:
Copy code The code is as follows:
mixed key(array array)

The following example outputs the key of the $fruits array by iterating through the array and moving the pointer:
Copy code The code is as follows:
$fruits = array(" apple"=>"red", "banana"=>"yellow");
while ($key = key($fruits)) {
printf("%s
", $key) ;
next($fruits);
}
// apple
// banana

Note that the pointer will not move every time key() is called. For this purpose, the next() function needs to be used. The only function of this function is to complete the task of advancing the pointer.

11. Get the current array value current()
current() function returns the array value at the current pointer position in the array. Its form is as follows:
Copy code The code is as follows:
mixed current(array array)

Let’s modify the previous example. This time we want to get the array value:
Copy code The code is as follows:
$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()
each() function returns the current key/value pair of input_array and advances the pointer one position. Its form is as follows:
Copy code The code 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.
Copy the code The code is as follows:
$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:
Copy code The code is as follows:
$fruits = array("apple", "banana", "orange", "pear");
reset($fruits);
while (list($key, $val) = each($fruits))
{
echo "$key => $val
";
}
// 0 => apple
// 1 => banana
// 2 => orange
// 3 => pear

Because assigning an array to another array will reset the original array pointer, so in the above example if we are looping Internally assigning $fruits to another variable will result in 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:
Copy code The code is as follows:
boolean in_array(mixed needle,array haystack[,boolean strict]);

Look at the following example to find whether the variable apple is already in the array. If it is, output a piece of information :
Copy code The code is as follows:
$fruit = "apple";
$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:
Copy code The code is as follows:
boolean array_key_exists(mixed key,array array);

The following example will search for apple in the array key, and if found, the color of the fruit will be output:
Copy code The code is as follows:
$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

15. array_search() function
array_search() function searches in an array A specified value that returns the corresponding key if found, otherwise false. Its form is as follows:
Copy code The code is as follows:
mixed array_search(mixed needle,array haystack[,boolean strict])

The following example searches $fruits for a specific date (December 7), and if found, returns the corresponding State related information:
Copy code The code is as follows:
$fruits["apple"] = "red";
$fruits["banana"] = "yellow";
$fruits["watermelon"]="green";
$founded = array_search("green", $fruits);
if($founded)
printf("%s was founded on %s.",$founded, $fruits[$founded]);
//watermelon was founded on green.

16. array_keys() function
array_keys() function returns an array containing all keys found in the searched array. Its form is as follows:

Copy code The code is as follows:
array array_keys(array array[,mixed search_value])

If the optional parameter search_value is included, only keys matching the value will be returned. The following example will output all arrays found in the $fruit array:
Copy code The code is as follows:
$fruits["apple"] = "red";
$fruits["banana"] = "yellow";
$fruits[ "watermelon"]="green";
$keys = array_keys($fruits);
print_r($keys);
//Array ( [0] => apple [1] => banana [2] => ; watermelon )

17. array_values() function
array_values() function returns all the values ​​in an array and automatically provides a numerical index for the returned array. Its form is as follows:
Copy code The code is as follows:
array array_values(array array)

The following example will get the value of each element found in $fruits:
Copy code The code is as follows:
$fruits["apple"] = " red";
$fruits["banana"] = "yellow";
$fruits["watermelon"]="green";
$values ​​= array_values($fruits);
print_r($values);
//Array ( [0] => red [1] => yellow [2] => green )

Sometimes we need to expand an array, or delete part of the array. PHP provides some functions for expanding and shrinking arrays. These functions provide convenience for programmers who wish to emulate various queue implementations (FIFO, LIFO). As the name suggests, the function names of these functions (push, pop, shift, and unshift) clearly reflect their functions.
PS: The traditional queue is a data structure. The order of deleting elements and adding elements is the same, which is called first-in-first-out, or FIFO. In contrast, a stack is another data structure in which elements are removed in the reverse order in which they were added. This becomes last-in-first-out, or LIFO.


18. Add elements to the head of the array
array_unshift() function adds elements to the head of the array. All existing numeric keys are modified to reflect their new positions in the array, but associated keys are not affected. Its form is as follows:
Copy code The code is as follows:
int array_unshift(array array,mixed variable[,mixed variable])

The following example adds two kinds of fruits in front of the $fruits array:
Copy code The code is as follows:
$fruits = array("apple","banana");
array_unshift($fruits,"orange","pear")
// $fruits = array("orange","pear","apple","banana") ;

19. Add elements to the end of the array
The return value of the array_push() function is int type, which is the number of elements in the array after pushing the data. You can pass multiple variables as parameters to this function and push it into the array at the same time. Multiple variables. Its form is:
Copy code The code is as follows:
(array array,mixed variable [,mixed variable...])

The following example adds two more fruits to the $fruits array:
Copy code The code is as follows:
$fruits = array("apple","banana");
array_push($fruits,"orange","pear")
//$fruits = array("apple","banana","orange","pear ")

20. Delete value from array head
array_shift() function deletes and returns the element found in the array. The result is that if numeric keys are used, all corresponding values ​​are shifted down, while arrays using associative keys are not affected. Its form is
Copy code The code is as follows:
mixed array_shift(array array)

The following example deletes the first element apple in the $fruits array:
Copy code The code is as follows:
$fruits = array("apple", "banana","orange","pear");
$fruit = array_shift($fruits);
// $fruits = array("banana","orange","pear")
// $fruit = " apple";

21. Delete elements from the end of the array
array_pop() function deletes and returns the last element of the array. Its form is:
Copy code The code is as follows:
mixed array_pop(aray target_array);

The following example deletes the last state from the $states array:
Copy code The code is as follows:
$fruits = array("apple", "banana","orange","pear");
$fruit = array_pop($fruits);
//$fruits = array("apple","banana","orange");
//$fruit = "pear";

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template