Home  >  Article  >  php教程  >  PHP array manipulation (merge, split, append, search, delete, etc.)

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

WBOY
WBOYOriginal
2016-08-04 08:53:191120browse

1. Merge arrays

The

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:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. 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.

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruits = array("apple","banana","pear");
  2. $numbered = array("1","2","3");
  3. $cards = array_merge($fruits, $numbered);
  4. print_r($cards);
  5. // output
  6. //Array ([0] => apple [1] => banana [2] => pear [3] => 1 [4] => 2 [5] => 3 )
  7. ?>

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:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. array array_merge_recursive(array array1,array array2[…,array arrayN])

Program examples are as follows:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruit1 = array("apple" => "red", "banana" => "yellow");
  2. $fruit2 = array("pear" => "yellow", "apple" => "green");
  3. $result = array_merge_recursive($fruit1, $fruit2);
  4. print_r($result);
  5. // output
  6. // Array ( [apple] => Array ( [0] => red [1] => green ) [banana] => yellow [pear] => yellow )
  7. ?>

Now the key apple points to an array consisting of two indexed arrays of color values.

3. Connect arrays

The

array_combine() function will get a new array, which consists of a set of submitted keys and corresponding values. Its form is:

Java code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. 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

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $name = array("apple", "banana", "orange");
  2. $color = array("red", "yellow", "orange");
  3. $fruit = array_combine($name, $color);
  4. print_r($fruit);
  5. // output
  6. // Array ( [apple] => red [banana] => yellow [orange] => orange )
  7. ?>

4. Split array array_slice()

The

array_slice() function will return a part of the array, starting from the key offset and ending at offset+length. Its form:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. 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:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1.   
  2. $fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");  
  3. $subset = array_slice($fruits, 3);  
  4. print_r($subset);  
  5.   
  6. // output  
  7. // Array ( [0] => Pear [1] => Grape [2] => Lemon [3] => Watermelon )  
  8. ?>  

 

然后我们使用下负长度:

Php代码  PHP array manipulation (merge, split, append, search, delete, etc.)
  1.   
  2. $fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");  
  3. $subset = array_slice($fruits, 2, -2);  
  4. print_r($subset);  
  5.   
  6. // output  
  7. // Array ( [0] => Orange [1] => Pear [2] => Grape )  
  8. ?>  

 

5. 接合数组 array_splice()

array_splice()函数会删除数组中从offset开始到offset+length 结束的所有元素,并以数组的形式返回所删除的元素。其形式为:

Php代码  PHP array manipulation (merge, split, append, search, delete, etc.)
  1. 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的位置结束。实例如下:

Php代码  PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");
  2. $subset = array_splice($fruits, 4);
  3. print_r($fruits);
  4. print_r($subset);
  5. // output
  6. // Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Pear )
  7. // Array ( [0] => Grape [1] => Lemon [2] => Watermelon )
  8. ?>

You can use the optional parameter replacement to specify the array to replace the target part. Examples are as follows:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruits = array("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon");
  2. $subset = array_splice($fruits, 2, -1, array("Green Apple", "Red Apple"));
  3. print_r($fruits);
  4. print_r($subset);
  5. // output
  6. // Array ( [0] => Apple [1] => Banana [2] => Green Apple [3] => Red Apple [4] => Watermelon )
  7. //Array ([0] => Orange [1] => Pear [2] => Grape [3] => Lemon )
  8. ?>

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:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. 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:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruit1 = array("Apple","Banana","Orange");
  2. $fruit2 = array("Pear","Apple","Grape");
  3. $fruit3 = array("Watermelon","Orange","Apple");
  4. $intersection = array_intersect($fruit1, $fruit2, $fruit3);
  5. print_r($intersection);
  6. // output
  7. // Array ( [0] => Apple )
  8. ?>

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:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. 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:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruit1 = array("red"=>"Apple","yellow"=>"Banana","orange"=>"Orange");
  2. $fruit2 = array("yellow"=>"Pear","red"=>"Apple","purple"=>"Grape");
  3. $fruit3 = array("green"=>"Watermelon","orange"=>"Orange","red"=>"Apple");
  4. $intersection = array_intersect_assoc($fruit1, $fruit2, $fruit3);
  5. print_r($intersection);
  6. // output
  7. //Array ( [red] => Apple )
  8. ?>

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().

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. array array_diff(array array1,array array2[,arrayN…])

Examples are as follows:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruit1 = array("Apple","Banana","Orange");
  2. $fruit2 = array("Pear","Apple","Grape");
  3. $fruit3 = array("Watermelon","Orange","Apple");
  4. $intersection = array_diff($fruit1, $fruit2, $fruit3);
  5. print_r($intersection);
  6. // output
  7. // Array ( [1] => Banana )
  8. ?>

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:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. 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.

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruit1 = array("red"=>"Apple","yellow"=>"Banana","orange"=>"Orange");
  2. $fruit2 = array("yellow"=>"Pear","red"=>"Apple","purple"=>"Grape");
  3. $fruit3 = array("green"=>"Watermelon","orange"=>"Orange","red"=>"Apple");
  4. $intersection = array_diff_assoc($fruit1, $fruit2, $fruit3);
  5. print_r($intersection);
  6. // output
  7. //Array ( [yellow] => Banana )
  8. ?>

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()

The

key() function returns the key at the current pointer position in input_array. Its form is as follows:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. mixed key(arrayarray)

The following example outputs the keys of the $fruits array by iterating over the array and moving the pointer:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruits = array("apple"=>"red", "banana"=>"yellow");
  2. while ($key = key($fruits)) {
  3. printf("%s
    ", $key);
  4. next($fruits);
  5. }
  6. // apple
  7. // 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:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. mixed current(arrayarray)

Let’s modify the previous example. This time we want to get the array value:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruits = array("apple"=>"red", "banana"=>"yellow");
  2. while ($fruit = current($fruits)) {
  3. printf("%s
    ", $fruit);
  4. next($fruits);
  5. }
  6. // red
  7. //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:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. 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.

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruits = array("apple", "banana", "orange", "pear");
  2. print_r (each($fruits));
  3. //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:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruits = array("apple", "banana", "orange", "pear");
  2. reset($fruits);
  3. while (list($key, $val) = each($fruits))
  4.                                      ~
  5. }
  6. // 0 => apple
  7. // 1 => banana
  8. // 2 => orange
  9. // 3 => pear
  10. 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.
  11. 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

boolean in_array(mixed needle,
array haystack[,boolean strict]);
PHP array manipulation (merge, split, append, search, delete, etc.)
  1. Look at the following example to find whether the variable apple is already in the array. If it is, output a piece of information:
Php code

$fruit =
"apple"; PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruits = array("apple","banana","orange",
  2. "pear");
  3. if( in_array($fruit,$fruits) )
  4. echo "$fruit is already in the array";
  5. 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

boolean
array_key_exists(mixed key,
array PHP array manipulation (merge, split, append, search, delete, etc.)array);
  1. The following example will search for apple in the array key, and if found, will output the color of this fruit:
Php code

  1. $fruit["apple"] = "red";
  2. $fruit["banana"] = "yellow";
  3. $fruit["pear"] = "green";
  4. if(array_key_exists("apple", $fruit)){
  5. printf("apple's color is %s",$fruit["apple"]);
  6. }
  7. //apple's color is red

15. array_search() function

The

array_search() function searches for a specified value in an array and returns the corresponding key if found, otherwise it returns false. Its form is as follows:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. mixed array_search(mixed needle,array haystack[,boolean strict])

The following example searches $fruits for a specific date (December 7), and if found, returns relevant information for the corresponding state:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruits["apple"] = "red";
  2. $fruits["banana"] = "yellow";
  3. $fruits["watermelon"]="green";
  4. $founded = array_search("green", $fruits);
  5. if($founded)
  6.  printf("%s was found on %s.",$founded, $fruits[$founded]);
  7. //watermelon was found 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:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. array array_keys(array array[,mixed search_value])

If you include the optional parameter search_value, only keys matching that value will be returned. The following example will output all arrays found in the $fruit array:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruits["apple"] = "red";
  2. $fruits["banana"] = "yellow";
  3. $fruits["watermelon"]="green";
  4. $keys = array_keys($fruits);
  5. print_r($keys);
  6. //Array ( [0] => apple [1] => banana [2] => watermelon )

17. array_values() function

The

array_values() function returns all values ​​in an array and automatically provides numerical indexes for the returned array. Its form is as follows:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. array array_values(array array)

The following example will get the value of each element found in $fruits:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruits["apple"] = "red";
  2. $fruits["banana"] = "yellow";
  3. $fruits["watermelon"]="green";
  4. $values ​​= array_values($fruits);
  5. print_r($values);
  6. //Array ([0] => red [1] => yellow [2] => green )

Sometimes we need to expand an array or delete a 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:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. int array_unshift(array array,mixed variable[,mixed variable])

The following example adds two fruits in front of the $fruits array:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruits = array("apple","banana");
  2. array_unshift($fruits,"orange","pear")
  3. // $fruits = array("orange","pear","apple","banana");

19. Add elements to the end of the array

The return value of the

array_push() function is of type int, 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 multiple variables into the array at the same time. Its form is:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. (array array,mixed variable [,mixed variable...])

The following example adds two more fruits to the $fruits array:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruits = array("apple","banana");
  2. array_push($fruits,"orange","pear")
  3. //$fruits = array("apple","banana","orange","pear")

20. Delete value from array head

array_shift() function removes and returns the element found in the array. The result is that if you are using numeric keys, all corresponding values ​​are shifted down, while arrays using associative keys are not affected. Its form is

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. mixed array_shift(array array)

The following example deletes the first element apple in the $fruits array:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruits = array("apple","banana","orange","pear");
  2. $fruit = array_shift($fruits);
  3. // $fruits = array("banana","orange","pear")
  4. // $fruit = "apple";

21. Delete elements from the end of the array

array_pop() function removes and returns the last element of the array. Its form is:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. mixed array_pop(aray target_array);

The following example removes the last state from the $states array:

Php code PHP array manipulation (merge, split, append, search, delete, etc.)
  1. $fruits = array("apple","banana","orange","pear");
  2. $fruit = array_pop($fruits);
  3. //$fruits = array("apple","banana","orange");
  4. //$fruit = "pear";

Statement:
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
Previous article:In DEDECMS, channel tagNext article:In DEDECMS, channel tag