PHP Learning with notes 4

Source: Internet
Author: User
Tags pear

PHP operation Array (merge, Split, append, find, delete, etc.)
      Blog Category:
    • Php/pear/mysql/node.js
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:

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.

<?php$fruits = Array ("Apple", "banana", "pear"), $numbered = Array ("1", "2", "3"), $cards = Array_merge ($fruits, $ Numbered);p Rint_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 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:

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

The program examples are as follows:

<?php$fruit1 = Array ("Apple" = "red", "banana" = "yellow"), $fruit 2 = Array ("pear" + "yellow", "apple" =  "Green"); $result = Array_merge_recursive ($fruit 1, $fruit 2);p Rint_r ($result);//output//Array ([Apple] = Array ([0] + red [1] = + green) [banana] = yellow [pear] = yellow)?>

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:

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

<?php$name = Array ("Apple", "banana", "orange"), $color = Array ("Red", "yellow", "orange"), $fruit = Array_combine ($ Name, $color);p Rint_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 with the key offset and ending at the offset+length position. Its form:

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:

<?php$fruits = Array ("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon"), $subset = Array_slice ($ Fruits, 3);p Rint_r ($subset);//output//Array ([0] = Pear [1] = = Grape [2] = = Lemon [3] = watermelon)?>

Then we use the following negative length:

<?php$fruits = Array ("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon"), $subset = Array_slice ($ Fruits, 2,-2);p Rint_r ($subset);//output//Array ([0] = Orange [1] = Pear [2] = Grape)?>

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:

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:

<?php$fruits = Array ("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon"), $subset = Array_splice ($ Fruits, 4);p Rint_r ($fruits);p rint_r ($subset);//output//Array ([0] = Apple [1] = Banana [2] = Orange [3] =&G T Pear)//Array ([0] = Grape [1] = Lemon [2] = = Watermelon)?>

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

<?php$fruits = Array ("Apple", "Banana", "Orange", "Pear", "Grape", "Lemon", "Watermelon"), $subset = Array_splice ($ Fruits, 2,-1, Array ("Green Apple", "Red Apple");p Rint_r ($fruits);p rint_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)?>

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:

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:

<?php$fruit1 = 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);p Rint_r ($intersection);// output//Array ([0] = Apple)?>

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:

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:

<?php$fruit1 = Array ("Red" = "Apple", "yellow" = "Banana", "orange" = "orange"), $fruit 2 = Array ("Yellow" = > "Pear", "Red" and "Apple", "Purple" and "Grape"); $fruit 3 = Array ("green" = "watermelon", "orange" + "orange" "Red" = "Apple"), $intersection = Array_intersect_assoc ($fruit 1, $fruit 2, $fruit 3);p Rint_r ($intersection);// output//Array ([red] = Apple)?>

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

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

Examples are as follows:

<?php$fruit1 = 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);p Rint_r ($intersection);// output//Array ([1] = Banana)?>

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:

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.

<?php$fruit1 = Array ("Red" = "Apple", "yellow" = "Banana", "orange" = "orange"), $fruit 2 = Array ("Yellow" = > "Pear", "Red" and "Apple", "Purple" and "Grape"); $fruit 3 = Array ("green" = "watermelon", "orange" + "orange" "Red" = "Apple"), $intersection = Array_diff_assoc ($fruit 1, $fruit 2, $fruit 3);p Rint_r ($intersection);//output// Array ([yellow] = Banana)?>

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:

Mixed key (array array)

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

$fruits = Array ("Apple" = "red", "banana" = "yellow"), while ($key = key ($fruits)) {printf ("%s <br/>", $key); n Ext ($fruits);} Apple//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:

Mixed current (array array)

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

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:

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.

$fruits = Array ("Apple", "banana", "orange", "pear");p rint_r (each ($fruits));//Array ([1] = apple [value] = AP ple [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:

$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 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:

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:

$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, 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:

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:

$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

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:

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:

$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:

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:

$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:

Array array_values (array array)

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

$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 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:

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

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

$fruits = Array ("Apple", "banana"), Array_unshift ($fruits, "orange", "pear")//$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:

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

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

$fruits = Array ("Apple", "banana"), Array_push ($fruits, "orange", "pear")//$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

Mixed Array_shift (array array)

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

$fruits = Array ("Apple", "banana", "orange", "pear"), $fruit = Array_shift ($fruits),//$fruits = Array ("Banana", "orange", "Pear")//$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:

Mixed Array_pop (Aray target_array);

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

$fruits = Array ("Apple", "banana", "orange", "pear"), $fruit = Array_pop ($fruits);//$fruits = Array ("Apple", "banana", " Orange ");//$fruit =" pear ";

PHP Learning with notes 4

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.