PHP Operations Array (merge, Split, append, find, delete, etc.) _php tips

Source: Internet
Author: User
Tags pear
1. Merging Arrays
The Array_merge () function merges the arrays together, returning a federated array. The resulting array begins with the first input array parameter and is forced in the order in which the following array parameters appear. In the form of:
Copy Code code 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 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 a numeric key name, the subsequent value will not overwrite the original value, but append to the back.
If only one array is given and the array is a numeric index, the key name is sequentially indexed.
Copy Code code 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 array
The array_merge_recursive () function is the same as the Array_merge () and can combine two or more numbers together to form a federated array. 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 pairs, replacing the key/value pairs 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 to append the array recursively. In the form of:

Copy Code code as follows:

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

Examples of programs are as follows:
Copy Code code as follows:

<?php
$fruit 1 = Array ("Apple" => "red", "banana" => "yellow");
$fruit 2 = Array ("pear" => "yellow", "apple" => "green");
$result = array_merge_recursive ($fruit 1, $fruit 2);
Print_r ($result);
Output
Array ([Apple] => Array ([0] => red [1] => green) [Banana] => yellow [pear] => yellow)
?>

Now the key Apple points to an array of two color values indexed by the array.
3. Connection array
The Array_combine () function gets a new array that consists of a set of committed keys and corresponding values. In the form of:
Copy Code code as follows:

Array Array_combine (array keys,array values)

Note that two input arrays must be of the same size and cannot be empty. Example below
Copy Code code 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-fraction Group Array_slice ()
The Array_slice () function returns a portion of the array, starting at the key offset and ending at the offset+length position. Its form:

Copy Code code as follows:

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

When offset is positive, the split begins at the offset position at 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 will start at offset until the last element of the array. If length is given and is positive, it ends at the offset+length position from the beginning of the array. Conversely, if length is given and is negative, the-|length| position of Count (Input_array) from the beginning of the array ends. Consider an example:
Copy Code code 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 negative length:
Copy Code code 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. Splice array Array_splice ()
The Array_splice () function deletes all elements in the array from offset to the end of Offset+length, and returns the deleted elements as an array. In the form of:
Copy Code code as follows:

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

When offset is positive, the splice starts at the offset position at the beginning of the array and when offset is negative, the engagement starts at the offset position at 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 engagement ends at the offset + leng th position at the beginning of the array. Conversely, if length is given and a negative value, the binding ends at the position of Count (Input_array)-length from the beginning of the array. Examples are as follows:
Copy Code code 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 optional parameter replacement to specify an array to replace the target part. Examples are as follows:
Copy Code code 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)
?>

You can clearly see how this function is used from the program.

6. Array intersection array_intersect ()
The Array_intersect () function returns an array of reserved keys that consist of only the values that appear in the first array and that appear in each of the other input arrays. The form is as follows:

Copy Code code as follows:

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

The following example returns all the fruits appearing in the $fruit1 array and appearing in $fruit2 and $fruit3:
Copy Code code as follows:

<?php
$fruit 1 = Array ("Apple", "Banana", "Orange");
$fruit 2 = Array ("Pear", "Apple", "Grape");
$fruit 3 = Array ("Watermelon", "Orange", "Apple");
$intersection = Array_intersect ($fruit 1, $fruit 2, $fruit 3);
Print_r ($intersection);
Output
Array ([0] => Apple)
?>

The Array_intersect () function thinks that they are 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 essentially the same as Array_intersect (), except that he also considers the key 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:

Copy Code code 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:
Copy Code code as follows:

<?php
$fruit 1 = Array ("Red" => "Apple", "Yellow" => "Banana", "Orange" => "Orange");
$fruit 2 = Array ("Yellow" => "Pear", "Red" => "Apple", "Purple" => "Grape");
$fruit 3 = Array ("green" => "watermelon", "orange" => "orange", "Red" => "Apple");
$intersection = Array_intersect_assoc ($fruit 1, $fruit 2, $fruit 3);
Print_r ($intersection);
Output
Array ([red] => Apple)
?>

8. Array difference set Array_diff ()
function Array_diff () returns a value that appears in the first array but not in the other input arrays. This function is the opposite of Array_intersect ().
Copy Code code as follows:

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

Examples are as follows:
Copy Code code as follows:

<?php
$fruit 1 = Array ("Apple", "Banana", "Orange");
$fruit 2 = Array ("Pear", "Apple", "Grape");
$fruit 3 = Array ("Watermelon", "Orange", "Apple");
$intersection = Array_diff ($fruit 1, $fruit 2, $fruit 3);
Print_r ($intersection);
Output
Array ([1] => Banana)
?>

9. The difference set of associative array Array_diff_assoc ()

The function Array_diff_assoc () is essentially the same as the Array_diff (), except that it also considers the key of the array when it is compared. Therefore, key/value pairs that appear only in the first array and no longer in the other input arrays are returned to the result array. The form is as follows:
Copy Code code as follows:

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

The following example returns only [yellow] => Banana because this particular key/value pair appears in $fruit1 and does not exist in both $fruit2 and $fruit3.
Copy Code code as follows:

<?php
$fruit 1 = Array ("Red" => "Apple", "Yellow" => "Banana", "Orange" => "Orange");
$fruit 2 = Array ("Yellow" => "Pear", "Red" => "Apple", "Purple" => "Grape");
$fruit 3 = Array ("green" => "watermelon", "orange" => "orange", "Red" => "Apple");
$intersection = Array_diff_assoc ($fruit 1, $fruit 2, $fruit 3);
Print_r ($intersection);
Output
Array ([yellow] => Banana)
?>

The enumeration group is often used in the process of using arrays. It's not surprising that PHP provides a number of functions to meet the requirements, usually by traversing the array and getting the keys or values (or both). Many functions can accomplish two tasks, not only to get the key or the value of the current pointer position, but also to move the pointer down to an appropriate position.

10. Get current Array key ()
The key () function returns the keys in the input_array where the current pointer is located. The form is as follows:
Copy Code code as follows:

Mixed key (array array)

The following example uses the iteration to process the array and move the pointer to output the key of the $fruits array:
Copy Code code 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 each time the key () is invoked. To do this you need to use the next () function, the only function of which is to complete the task of pushing the pointer.

11. Get Current Array value
The current () function returns the value of the array in the array at which the pointer is currently positioned. The form is as follows:
Copy Code code as follows:

Mixed current (array array)

Let's revise the previous example, this time to get the array value:
Copy Code code as follows:

$fruits = Array ("Apple" => "red", "banana" => "yellow");
while ($fruit = current ($fruits)) {
printf ("%s <br/>", $fruit);
Next ($fruits);
}
Red
Yellow

12. Get current array keys and values each ()
The each () function returns the current key/value pair of Input_array and pushes the pointer one position. The form is as follows:
Copy Code code as follows:

Array each (array array)

The returned array contains four keys, the key 0 and key contain the key names, and the key 1 and value contain the corresponding data. Returns False if the previous pointer at the end of the array executes each ().
Copy Code code 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 the list () to traverse an array. This example is similar to the previous example, but the loop outputs the entire array:
Copy Code code as follows:

$fruits = Array ("Apple", "banana", "orange", "pear");
Reset ($fruits);
while (the list ($key, $val) = each ($fruits))
{
echo "$key => $val <br/>";
}
0 => Apple
1 => Banana
2 => Orange
3 => Pear

Because assigning an array to another array resets the original array pointer, so in the previous example, if we assign $fruits to another variable within the loop, we 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 operations. Here are a few related functions.

In_array () function
The In_array () function searches for a specific value in an array rollup and returns False if the value is found to return true. The form is as follows:
Copy Code code as follows:

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

Look at the example below to find out whether the variable Apple is already in the array, and if it is, output a piece of information:
Copy Code code as follows:

$fruit = "Apple";
$fruits = Array ("Apple", "banana", "orange", "pear");
if (In_array ($fruit, $fruits))
echo "$fruit already in array";

The third argument 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 it returns false. The form is as follows:
Copy Code code as follows:

Boolean array_key_exists (mixed Key,array array);

The following example searches for Apple in the array key and, if found, prints the color of the fruit:
Copy Code code 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

Array_search () function
The Array_search () function searches an array for a specified value and returns False if it finds the corresponding key. The form is as follows:
Copy Code code as follows:

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:
Copy Code code as follows:

$fruits ["apple"] = "red";
$fruits ["banana"] = "yellow";
$fruits ["Watermelon"]= "green";
$founded = Array_search ("green", $fruits);
if ($founded)
printf ("%s is founded on%s.", $founded, $fruits [$founded]);
Watermelon is 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:

Copy Code code as follows:

Array Array_keys (array array[,mixed search_value])

If you include an optional parameter search_value, only the key that matches the value is returned. The following example outputs all the arrays found in the $fruit array:
Copy Code code 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)

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:
Copy Code code as follows:

Array array_values (array array)

The following example gets the values of the elements found in the $fruits:
Copy Code code 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 extend an array, or delete part of the array, and PHP provides some functions for expanding 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 suggests, the function names of these functions (push, pop, shift, and unshift) clearly reflect their role.
PS: The traditional queue is a data structure, delete elements and add the same order of elements, called advanced First Out, or FIFO. Instead, stacks are another type of data structure in which the order in which elements are deleted is in contrast to the order in which they were added, which becomes LIFO, or LIFO.


18. Adding elements to the array header
The Array_unshift () function adds an element to the array header. All of your numeric keys are modified accordingly to reflect their new position in the array, but the association keys are unaffected. The form is as follows:
Copy Code code as follows:

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

The following example adds two kinds of fruit to the front of the $fruits array:
Copy Code code as follows:

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

19. Add element at end of array
The return value of the Array_push () function is int, is the number of elements in the array after the data is pressed, you can pass multiple variables as arguments for this function, and press multiple variables into the array. In the form of:
Copy Code code as follows:

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

The following example adds two more fruits to the $fruits array:
Copy Code code as follows:

$fruits = Array ("Apple", "banana");
Array_push ($fruits, "orange", "pear")
$fruits = Array ("Apple", "banana", "orange", "pear")

20. Delete a value from the array header
The Array_shift () function deletes and returns the elements found in the array. As a result, if you are using a numeric health, all corresponding values are moved down, and the array using the association keys is unaffected. Its form as
Copy Code code as follows:

Mixed Array_shift (array array)

The following example deletes the first element in the $fruits array, Apple:
Copy Code code as follows:

$fruits = Array ("Apple", "banana", "orange", "pear");
$fruit = Array_shift ($fruits);
$fruits = Array ("Banana", "orange", "pear")
$fruit = "Apple";

21. Delete an element from the end of an array
The Array_pop () function deletes and returns the last element of the array. In the form of:
Copy Code code as follows:

Mixed Array_pop (Aray target_array);

The following example deletes the last state from the $states array:
Copy Code code 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.