PHP array functions (merge, split, append, search, delete, etc)

Source: Internet
Author: User
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: 1. Merge the array


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:

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.

  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:

array array_merge_recursive(array array1,array array2[…,array arrayN])


The program example is as follows:

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

array array_combine(array keys,array values)


Note: the two input arrays must be of the same size and cannot be empty. Example:

  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:

array array_slice (array 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:

  Pear [1] => Grape [2] => Lemon [3] => Watermelon )  ?>

Then we use the following negative length:

  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:

array array_splice ( array 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:

  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:

  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:

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:

  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:

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:

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

array array_diff(array array1,array array2[,arrayN…])


Example:

  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:

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.

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

mixed key(array array)


The following example outputs the key of the $ fruits array by iteratively processing the array and moving the pointer:

$fruits = array("apple"=>"red", "banana"=>"yellow");  while ($key = key($fruits)) {      printf("%s 
", $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:

mixed current(array array)

Next, modify the previous example to obtain the array value:

$fruits = array("apple"=>"red", "banana"=>"yellow");  while ($fruit = current($fruits)) {      printf("%s 
", $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:

array each(array 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.

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

$fruits = array("apple", "banana", "orange", "pear");  reset($fruits);    while (list($key, $val) = each($fruits))      {          echo "$key => $val
"; } // 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:


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:

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

boolean array_key_exists(mixed key,array array);


The following example searches for apple in the array key. if it is found, the color of the fruit is output:

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

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:

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

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 )

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:

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

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

In the following example, two fruits are added before the $ fruits array:

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

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

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

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

mixed array_shift(array array)

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

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

mixed array_pop(aray target_array);

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

$fruits = array("apple","banana","orange","pear");  $fruit = array_pop($fruits);  //$fruits = array("apple","banana","orange");  //$fruit = "pear";

The above is the PHP array function (merge, split, append, search, delete, etc.) content. For more information, please follow the PHP Chinese network (www.php1.cn )!

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.