Php Operation Array (merge, split, append, search, delete, etc)

Source: Internet
Author: User

1. Merge Arrays
The array_merge () function combines arrays and returns a union array. The obtained array starts with the first input array parameter and is immediately added according to the order in which the following array parameters appear. The format is: Copy codeThe Code is as follows: array array_merge (array array1 array2 ..., ArrayN)

This function combines the units of one or more arrays. The values of an array are appended to the values of the previous array. Returns an array of results.
If the input array contains the same string key name, the value after the key name overwrites the previous value. However, if the array contains a number key name, the subsequent values will not overwrite the original values, but will be appended to the back.
If only one array is assigned and the array is indexed by number, the key name is re-indexed continuously.Copy codeThe Code is as follows: <? Php
$ 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 an array
The array_merge_recursive () function is the same as the array_merge () function. Two or more numbers can be combined to form a combined array. the difference between the two is that when a key in an input array already exists in the result array, the function will adopt different processing methods. array_merge () overwrites the existing key/value pairs and replaces them with the key/value pairs in the current input array. array_merge_recursive () merges the two values, form a new array and use the original key as the array name. Another form of array merging is recursively appending an array. The format is:

Copy codeThe Code is as follows: array array_merge_recursive (array array1, array array2 [..., Array arrayN])

The program example is as follows:Copy codeThe Code is as follows: <? Php
$ 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 color values.
3. connect to an array
The array_combine () function returns a new array consisting of a set of submitted keys and corresponding values. The format is:Copy codeThe Code is as follows: array array_combine (array keys, array values)

Note: The two input arrays must be of the same size and cannot be empty. Example:Copy codeThe Code is as follows: <? Php
$ 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 ()
The array_slice () function returns a part of the array, starting from the key offset and ending at the offset + length position. Form:

Copy codeThe Code is as follows: array array_slice (array, int offset [, int length])

When offset is a positive value, the split starts from the offset position starting from the array. If offset is a negative value, the split starts from the offset position at the end of the array. If the optional length parameter is omitted, the split starts from offset to the last element of the array. If length is given and it is a positive number, it will end at the offset + length position starting with the array. On the contrary, if length is given and it is a negative number, it ends at the count (input_array)-| length | position starting with the array. Consider an example:Copy codeThe Code is as follows: <? Php
$ 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 following negative length:Copy codeThe Code is as follows: <? Php
$ 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 deletes all elements in the array from offset to offset + length, and returns the deleted elements in an array. The format is:Copy codeThe Code is as follows: array array_splice (array, int offset [, length [, array replacement])

When offset is a positive value, the join starts from the offset position starting from the array. When offset is a negative value, the join starts from the offset position at the end of the array. If the optional length parameter is ignored, all elements from the offset position to the end of the array will be deleted. If length is given and it is a positive value, the join ends at the offset + leng th position starting with the array. Conversely, if length is given and it is a negative value, the combination ends at the position of count (input_array)-length starting with the array. Example:Copy codeThe Code is as follows: <? Php
$ 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 an array that replaces the target part. Example:Copy codeThe Code is as follows: <? Php
$ 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)
?>

The program clearly shows how to use this function.

6. array intersection array_intersect ()
The array_intersect () function returns an array with keys retained. This array is composed of only values that appear in the first array and appear in each other input array. The format is as follows:

Copy codeThe Code is as follows: array array_intersect (array array1, array array2 [, arrayN…])

The following example returns all fruits that appear in the $ fruit1 array and also appear in $ fruit2 and $ fruit3:Copy codeThe Code is as follows: <? Php
$ 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 considers the two elements to be identical only when they have the same data type.

7. array_intersect_assoc ()
The array_intersect_assoc () function is basically the same as the array_intersect () function, except that the array key is also considered during comparison. Therefore, only key/value pairs that appear in the first array and also appear in all other input arrays are returned to the result array.
The format is as follows:

Copy codeThe Code 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 $ fruit2 and $ fruit3 at the same time:Copy codeThe Code is as follows: <? Php
$ 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. array difference set array_diff ()
The array_diff () function returns a value that appears in the first array but does not exist in other input arrays. This function is opposite to array_intersect.Copy codeThe Code is as follows: array array_diff (array array1, array array2 [, arrayN…])

Example:Copy codeThe Code is as follows: <? Php
$ 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. array_diff_assoc ()

The array_diff_assoc () function is basically the same as the array_diff () function, except that the array key is also considered during comparison. Therefore, only key/value pairs that appear in the first array instead of other input arrays are returned to the result array. The format is as follows:Copy codeThe Code is as follows: array array_diff_assoc (array array1, array array2 [, arrayN…])

In the following example, only [yellow] => Banana is returned, because this special key/value pair exists in $ fruit1, and does not exist in $ fruit2 or $ fruit3.Copy codeThe Code is as follows: <? Php
$ 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 arrays, you often need to traverse arrays. It is usually necessary to traverse the array and obtain each key or value (or simultaneously obtain the key and value), so it is not surprising that PHP provides some functions to meet the needs. Many functions can complete two tasks, not only to obtain the key or value of the current pointer position, but also to move the pointer to the next appropriate position.

10. Get the current array key ()
The key () function returns the key where the current pointer is located in input_array. The format is as follows:Copy codeThe Code is as follows: mixed key (array)

The following example outputs the key of the $ fruits array by iteratively processing the array and moving the pointer:Copy codeThe Code is as follows: $ fruits = array ("apple" => "red", "banana" => "yellow ");
While ($ key = key ($ fruits )){
Printf ("% s <br/>", $ key );
Next ($ fruits );
}
// Apple
// Banana

Note that the pointer is not moved every time key () is called. Therefore, the next () function must be used to complete the task of advancing the pointer.

11. Get the current array value current ()
The current () function returns the array value of the current pointer position in the array. The format is as follows:Copy codeThe Code is as follows: mixed current (array)

Next, modify the previous example to obtain the array value:Copy codeThe Code is as follows: $ fruits = array ("apple" => "red", "banana" => "yellow ");
While ($ fruit = current ($ fruits )){
Printf ("% s <br/>", $ 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 pushes the pointer to a position. The format is as follows:Copy codeThe Code is as follows: array each (array)

The returned array contains four keys. Keys 0 and key contain the key name, while keys 1 and value contain the corresponding data. If the pointer before execution of each () is located at the end of the array, false is returned.Copy codeThe 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 combination with list () to traverse arrays. This example is similar to the previous example, but the entire array is output cyclically:Copy codeThe Code is as follows: $ fruits = array ("apple", "banana", "orange", "pear ");
Reset ($ fruits );
While (list ($ key, $ val) = each ($ fruits ))
{
Echo "$ key => $ val <br/> ";
}
// 0 => apple
// 1 => banana
// 2 => orange
// 3 => pear

Because the original array pointer is reset when an array is assigned to another array, if $ fruits is assigned to another variable in the previous example, an infinite loop will occur.
This completes the array traversal.

Searching, filtering, and searching array elements are common functions of Array Operations. The following describes several related functions.

13. in_array () function
The in_array () function searches for a specific value in an array. If this value is found, true is returned. Otherwise, false is returned. The format is as follows:Copy codeThe Code is as follows: boolean in_array (mixed needle, array haystack [, boolean strict]);

Let's take a look at the example below to check whether the variable apple is already in the array. If so, a piece of information is output:Copy codeThe 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 during search.

14. array_key_exists () function
If a specified key is found in an array, the array_key_exists () function returns true; otherwise, false. The format is as follows:Copy codeThe Code is as follows: boolean array_key_exists (mixed key, array );

The following example searches for apple in the array key. If it is found, the color of the fruit is output:Copy codeThe 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
The array_search () function searches for a specified value in an array. If yes, the corresponding key is returned. Otherwise, false is returned. The format is as follows:Copy codeThe Code is as follows: mixed array_search (mixed needle, array haystack [, boolean strict])

The following example searches for a specific date (December 7) in $ fruits. If it is found, information about the corresponding state is returned:Copy codeThe 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
The array_keys () function returns an array containing all the keys found in the searched array. The format is as follows:

Copy codeThe Code is as follows: array array_keys (array [, mixed search_value])

If the optional parameter search_value is included, only the key that matches the value is returned. The following example outputs all the arrays found in the $ fruit array:Copy codeThe 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
The array_values () function returns all values in an array and automatically provides a numerical index for the returned array. The format is as follows:Copy codeThe Code is as follows: array array_values (array)

The following example gets the values of each element found in $ fruits:Copy codeThe 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 a part of the array. PHP provides some functions for extending and downgrading the array. For programmers who want to simulate various queue implementations (FIFO and LIFO), these functions can be convenient. As the name suggests, the function names (push, pop, shift, and unshift) of these functions clearly reflect their functions.
PS: the traditional queue is a data structure. Deleting elements is in the same order as adding elements, which is called FIFO or FIFO. On the contrary, the stack is another data structure, in which the order in which elements are deleted is the opposite of the order when they are added, which is either backward-forward, FIFO, or LIFO.

18. add elements to the array Header
The array_unshift () function adds elements to the array header. All existing numeric keys are modified accordingly to reflect their new positions in the array, but the associated keys are not affected. The format is as follows:Copy codeThe Code is as follows: int array_unshift (array, mixed variable [, mixed variable])

In the following example, two fruits are added before the $ fruits array:Copy codeThe Code is as follows: $ fruits = array ("apple", "banana ");
Array_unshift ($ fruits, "orange", "pear ")
// $ Fruits = array ("orange", "pear", "apple", "banana ");

19. add elements at 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 data is pressed. For this function, multiple variables can be passed as parameters and multiple variables can be pushed to the array at the same time. The format is:Copy codeThe Code is as follows: (array, mixed variable [, mixed variable...])

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

20. Delete the value from the array Header
The array_shift () function deletes and returns the elements found in the array. The result is that if a numeric value is used, all corresponding values are moved down, And the Array Using the correlated key is not affected. The format isCopy codeThe Code is as follows: mixed array_shift (array)

The following example deletes the first element apple in the $ fruits array:Copy codeThe 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
The array_pop () function deletes the array and returns the last element of the array. The format is:Copy codeThe Code is as follows: mixed array_pop (aray target_array );

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.