PHP Array Operation method

Source: Internet
Author: User
Tags pear

1. Merging arrays

The Array_merge () function merges the arrays together to return an array of unions. The resulting array starts with the first input array parameter, forcing it sequentially in the order in which the array parameters appear later. The form is:

    1. Array Array_merge (array array1 array2...,arrayn)

This function merges the cells of one or more arrays, and the values in an array are appended to the previous array. Returns an array as the result.

If the input array has the same string key name, the value following the key name overrides the previous value. However, if the array contains numeric key names, subsequent values will not overwrite the original values, but are appended to the back.

If only one array is given and the array is a numeric index, the key name is re-indexed in a sequential manner.

    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 () and can combine two or more numbers together to form an array of unions. The difference between the two is that when a key in an input array is already in the result array, the function takes a different approach. Array_merge () overrides the previously existing key/value pair, replacing it with the key/value pair in the current input array, and array_merge_recursive () merges two values together to form a new array with the original key as the array name. There is also the form of an array merge, which is a recursive append array. The form is:

    1. Array array_merge_recursive (array Array1,array array2[...,array Arrayn])

The program examples are as follows:

    1. $fruit 1 = Array ("Apple" = "red", "banana" = "yellow");
    2. $fruit 2 = Array ("pear" + "yellow", "apple" = "green");
    3. $result = array_merge_recursive ($fruit 1, $fruit 2);
    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 of indexed arrays of two color values.

3. Connect an array

The Array_combine () function gets a new array that consists of a set of committed keys and corresponding values. The form is:

    1. Array Array_combine (array keys,array values)

Note that two input arrays must be of the same size and cannot be empty. Examples such as the following

    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 fraction Group Array_slice ()

The Array_slice () function returns a portion of the array, starting with the key offset and ending at the offset+length position. Its form:

    1. Array array_slice (array array, int offset[,int length])

When offset is positive, the split starts at offset from the beginning of the array, and if offset is a negative value, the split starts at the offset position at the end of the array. If the optional parameter length is omitted, the split starts at offset and continues to the last element of the array. If length is given and is positive, the offset+length position ends at the beginning of the array. Conversely, if length is given and is negative, the count (Input_array)-|length| position at the beginning of the array ends. Consider an example:

    1. $fruits = Array ("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "watermelon");
    2. $subset = Array_slice ($fruits, 3);
    3. Print_r ($subset);
    4. Output
    5. Array ([0] = Pear [1] = Grape [2] = = Lemon [3] = = Watermelon)
    6. ?>

Then we use the following negative length:

    1. $fruits = Array ("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "watermelon");
    2. $subset = Array_slice ($fruits, 2,-2);
    3. Print_r ($subset);
    4. Output
    5. Array ([0] = Orange [1] = Pear [2] = Grape)
    6. ?>

5. Junction array Array_splice ()

The Array_splice () function deletes all elements in the array from offset to end of Offset+length and returns the deleted element as an array. The form is:

    1. Array array_splice (array array, int Offset[,length[,array replacement])

When offset is positive, the join starts at offset from the beginning of the array, and when offset is negative, the join starts at the offset position from the end of the array. If the optional length parameter is omitted, all elements from the offset position to the end of the array are deleted. If length is given and positive, the join ends at offset + Leng th at the beginning of the array. Conversely, if length is given and is negative, the union ends at the position of Count (Input_array)-length from the beginning of the array. Examples are as follows:

    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 an array that supersedes the target part. Examples are as follows:

    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. ?>

From the program you can clearly see how this function is used.

6. Intersection of Arrays Array_intersect ()

The Array_intersect () function returns an array that retains the key, which consists only of the values that appear in the first array and that appear in each of the other input arrays. The form is as follows:

    1. Array array_intersect (array Array1,array array2[,arrayn ...])

The following example returns all the fruits that appear in the $fruit1 array and also appear in $fruit2 and $fruit3:

    1. $fruit 1 = Array ("Apple", "Banana", "Orange");
    2. $fruit 2 = Array ("Pear", "Apple", "Grape");
    3. $fruit 3 = Array ("Watermelon", "Orange", "Apple");
    4. $intersection = Array_intersect ($fruit 1, $fruit 2, $fruit 3);
    5. Print_r ($intersection);
    6. Output
    7. Array ([0] = Apple)
    8. ?>

The Array_intersect () function considers them to be the same only if the two elements 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 he also considers the keys of the array in the comparison. Therefore, only key/value pairs that appear in the first array and in all other input arrays are returned to the result array.

The form is as follows:

    1. Array Array_intersect_assoc (array Array1,array array2[,arrayn ...])

The following example returns all the key/value pairs that appear in the $fruit1 array and also in $fruit2 and $fruit3:

    1. $fruit 1 = Array ("Red" = "Apple", "yellow" = "Banana", "orange" and "Orange");
    2. $fruit 2 = Array ("Yellow" = "Pear", "red" = "Apple", "Purple" and "Grape");
    3. $fruit 3 = Array ("green" = "watermelon", "orange" and "orange", "Red" and "Apple");
    4. $intersection = Array_intersect_assoc ($fruit 1, $fruit 2, $fruit 3);
    5. Print_r ($intersection);
    6. Output
    7. Array ([red] = Apple)
    8. ?>

8. Array difference set Array_diff ()

The function Array_diff () returns a value that appears in the first array but not in the other input array. This function is opposite to Array_intersect ().

    1. Array Array_diff (array Array1,array array2[,arrayn ...])

Examples are as follows:

    1. $fruit 1 = Array ("Apple", "Banana", "Orange");
    2. $fruit 2 = Array ("Pear", "Apple", "Grape");
    3. $fruit 3 = Array ("Watermelon", "Orange", "Apple");
    4. $intersection = Array_diff ($fruit 1, $fruit 2, $fruit 3);
    5. Print_r ($intersection);
    6. Output
    7. Array ([1] = Banana)
    8. ?>

9. Difference set of associative arrays Array_diff_assoc ()

The function Array_diff_assoc () is basically the same as Array_diff (), except that it also considers the keys of the array when compared. Therefore, a key/value pair that appears only in the first array and no longer appears in the other input array is returned to the result array. The form is as follows:

    1. Array Array_diff_assoc (array Array1,array array2[,arrayn ...])

The following example returns only [yellow] + Banana, because this special key/value pair appears in $fruit1 and does not exist in $fruit2 and $fruit3.

    1. $fruit 1 = Array ("Red" = "Apple", "yellow" = "Banana", "orange" and "Orange");
    2. $fruit 2 = Array ("Yellow" = "Pear", "red" = "Apple", "Purple" and "Grape");
    3. $fruit 3 = Array ("green" = "watermelon", "orange" and "orange", "Red" and "Apple");
    4. $intersection = Array_diff_assoc ($fruit 1, $fruit 2, $fruit 3);
    5. Print_r ($intersection);
    6. Output
    7. Array ([yellow] = Banana)
    8. ?>

In the process of using arrays, you often need to go through the group. It's not surprising that PHP provides some functions to meet the requirements, usually by iterating through the array and getting the keys or values (or getting the keys and values at the same time). Many functions can accomplish two tasks, not only to get the key or value of the current pointer position, but also to move the pointer down an appropriate position.

10. Get the current Array key key ()

The key () function returns the keys at the position of the current pointer in Input_array. The form is as follows:

    1. Mixed key (array array)

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

    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 each time you call key (), the pointer is not moved. To do this, you need to use the next () function, which is the only function that completes the task of pushing the pointer.

11. Get the current array value of present ()

The current () function returns the array value in the array where the pointer is currently located. The form is as follows:

    1. Mixed current (array array)

The following changes the previous example, this time we want to get the array value:

    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 to a position. The form is as follows:

    1. Array each (array array)

The returned array contains four keys, key 0 and key contain the key names, and key 1 and value contain the corresponding data. Returns False if each () is executed before the pointer is at the end of the array.

    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 through the array. This example is similar to the previous example, but the loop outputs the entire array:

    1. $fruits = Array ("Apple", "banana", "orange", "pear");
    2. Reset ($fruits);
    3. while (list ($key, $val) = each ($fruits))
    4. {
    5. echo "$key and $val
      ";
    6. }
    7. 0 = Apple
    8. 1 = Banana
    9. 2 = Orange
    10. 3 = Pear

Because assigning an array to another array resets the original array pointer, so in the example above, if we assign the $fruits to another variable inside the loop, it will cause an infinite loop.

This completes the traversal of the array.

Finding, filtering, and searching array elements are some of the common features of array manipulation. Here are a few related functions.

In_array () function

The In_array () function searches for a specific value in an array rollup and returns True if this value is found, otherwise false. The form is as follows:

    1. Boolean In_array (mixed Needle,array Haystack[,boolean strict]);

Look at the following example, look for the variable if Apple is already in the array, and if so, output a piece of information:

    1. $fruit = "Apple";
    2. $fruits = Array ("Apple", "banana", "orange", "pear");
    3. if (In_array ($fruit, $fruits))
    4. echo "$fruit is already in the array";

The third parameter is optional, which forces In_array () to consider the type when searching.

array_key_exists () function

If a specified key is found in an array, the function array_key_exists () returns True, otherwise false is returned. The form is as follows:

    1. Boolean array_key_exists (mixed Key,array array);

The following example searches for Apple in the array key and, if found, outputs the color of the fruit:

    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

The . Array_search () function

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

    1. Mixed Array_search (mixed Needle,array Haystack[,boolean Strict])

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

    1. $fruits ["apple"] = "red";
    2. $fruits ["banana"] = "yellow";
    3. $fruits ["Watermelon"]= "green";
    4. $founded = Array_search ("green", $fruits);
    5. if ($founded)
    6. printf ("%s is founded on%s.", $founded, $fruits [$founded]);
    7. Watermelon was founded on green.

Array_keys () function

The Array_keys () function returns an array that contains all the keys found in the searched array. The form is as follows:

    1. Array Array_keys (array 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:

    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)

array_values () function

The Array_values () function returns all the values in an array and automatically provides a numeric index for the returned array. The form is as follows:

    1. Array array_values (array array)

The following example gets the values of each element found in $fruits:

    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 extend an array or delete part of the array, and PHP provides some functions for extending and shrinking the array. These functions can be handy for programmers who want to emulate a variety of queue implementations (FIFO, LIFO). As the name implies, the function names (push, pop, shift, and unshift) from these functions clearly reflect their role.

PS: A traditional queue is a data structure that removes elements in the same order that they are added, known as FIFO, first-in-the-line Instead, stacks are another data structure in which the order in which elements are removed is reversed in the order in which they were added, which becomes LIFO, or LIFO.

18. Adding 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 position in the array, but the association keys are not affected. The form is as follows:

    1. int Array_unshift (array array,mixed variable[,mixed variable])

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

    1. $fruits = Array ("Apple", "banana");
    2. Array_unshift ($fruits, "orange", "pear")
    3. $fruits = Array ("Orange", "pear", "apple", "banana");

19. Adding elements at 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 the data is pressed, and it is possible to pass multiple variables as arguments for this function, while pressing multiple variables into the array. The form is:

    1. (Array array,mixed variable [, mixed variable ...])

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

    1. $fruits = Array ("Apple", "banana");
    2. Array_push ($fruits, "orange", "pear")
    3. $fruits = Array ("Apple", "banana", "orange", "pear")

20. Removing values from the array header

The Array_shift () function deletes and returns the element found in the array. As a result, if you are using a numeric key, all corresponding values are moved down, and arrays that use the associated keys are not affected. In the form of

    1. Mixed Array_shift (array array)

The following example removes the first element from the $fruits array, Apple:

    1. $fruits = Array ("Apple", "banana", "orange", "pear");
    2. $fruit = Array_shift ($fruits);
    3. $fruits = Array ("Banana", "orange", "pear")
    4. $fruit = "Apple";

21. Deleting elements from the end of an array

The Array_pop () function deletes and returns the last element of the array. The form is:

    1. Mixed Array_pop (Aray target_array);

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

    1. $fruits = Array ("Apple", "banana", "orange", "pear");
    2. $fruit = Array_pop ($fruits);
    3. $fruits = Array ("Apple", "banana", "orange");
    4. $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.