Home > Backend Development > PHP Tutorial > PHP array manipulation (merge, split, append, search, delete, etc.)_PHP tutorial

PHP array manipulation (merge, split, append, search, delete, etc.)_PHP tutorial

WBOY
Release: 2016-07-21 15:16:58
Original
786 people have browsed it

1. Merge arrays
The array_merge() function merges arrays together and returns a combined array. The resulting array starts with the first input array parameter, and is added sequentially in the order in which subsequent array parameters appear. Its form is:

Copy code The code is as follows:

array array_merge (array array1 array2…,arrayN)

This function combines the cells of one or more arrays, and the values ​​in one array are appended to the previous array. Returns the resulting array.
If there is the same string key name in the input array, the value after the key name will overwrite the previous value. However, if the array contains numeric keys, the subsequent values ​​will not overwrite the original values ​​but will be appended to them.
If only an array is given and the array is numerically indexed, the key names are re-indexed in a consecutive manner.
Copy code The code is as follows:

$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
array_merge_recursive() function is the same as array_merge(), you can merge two Or multiple arrays are combined together to form a combined array. The difference between the two is that the function will handle it differently when a key in an input array already exists in the result array. array_merge() will overwrite the previously existing key/value pairs and replace them with the key/value pairs in the current input array, while array_merge_recursive() will merge the two values ​​together to form a new array with the original keys. as an array name. There is also a form of array merging, which is to recursively append arrays. Its form is:

Copy code The code is as follows:

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

The program example is as follows:
Copy code The 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 indexed arrays of color values.
3. Connect arrays
The array_combine() function will get a new array, which consists of a set of submitted keys and corresponding values. Its form is:
Copy code The code is as follows:

array array_combine(array keys, array values)

Note that the two input arrays must be of the same size and cannot be empty. The example is as follows
Copy the code The code is as follows:

$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 will return a part of the array, starting from the key offset and ending at the offset+length position. Its form:

Copy code The code is as follows:

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

When offset is a positive value, splitting will start from the offset position from the beginning of the array; if offset is a negative value, splitting will start from the offset position from the end of the array. If the optional length parameter is omitted, the split will start at offset and go to the last element of the array. If length is given and is positive, it ends at offset+length from the beginning of the array. Conversely, if length is given and is negative, it ends at count(input_array)-|length| from the beginning of the array. Consider an example:
Copy code The code is as follows:

$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 lower negative length:
Copy the code The code is as follows:

$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 will delete all elements in the array starting from offset and ending at offset+length, and Returns the removed elements as an array. Its form is:
Copy code The code is as follows:

array array_splice ( array array , int offset[,length[,array replacement]])

When offset is a positive value, the joining will start from the offset position from the beginning of the array. When offset is a negative value, the joining will start from the offset position from the end of the array. If the optional length parameter is omitted, all elements starting at offset position and ending at the end of the array will be removed. If length is given and is positive, the join ends at offset + leng th from the beginning of the array. Conversely, if length is given and is negative, the union will end count(input_array)-length from the beginning of the array. The example is as follows:
Copy code The code is as follows:

$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 )
?>

Optional parameter replacement can be used to specify the array to replace the target part. The example is as follows:
Copy code The code is as follows:

$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 to use this function from the program.

6. Intersection of arrays array_intersect()
The array_intersect() function returns an array that retains keys. This array only consists of keys that appear in the first array and are present in each other consists of values ​​that appear in each input array. Its form is as follows:

Copy code The code is as follows:

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

The following example will return all fruits that appear in the $fruit1 array and also appear in $fruit2 and $fruit3:
Copy code The code is as follows:

$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 will consider two elements to be the same only if they 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 it also considers the keys of the array in the comparison. Therefore, only key/value pairs that appear in the first array and also appear in all other input arrays are returned in the result array.
The form is as follows:

Copy code The 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 also appear in $fruit2 and $fruit3:
Copy code The code is as follows:

$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 array_diff()
The function array_diff() returns values ​​that appear in the first array but are not in other input arrays. This function is the opposite of array_intersect().
Copy code The code is as follows:

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

The example is as follows:
Copy code The code is as follows:

$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. Difference set of associative array array_diff_assoc()

Function array_diff_assoc() and array_diff() Basically the same, except it also considers the keys of the array when comparing. Therefore, only key/value pairs that appear in the first array but not in other input arrays are returned in the result array. Its form is as follows:
Copy code The code is as follows:

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

The following example only returns [yellow] => Banana, because this special key/value pair appears in $fruit1, but does not exist in $fruit2 or $fruit3.
Copy code The code is as follows:

$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 an array, you often need to traverse the array. It is often necessary to iterate through an array and get the individual keys or values ​​(or get both keys and values), so not surprisingly, PHP provides some functions for this purpose. Many functions perform two tasks, not only obtain the key or value at the current pointer position, but also move the pointer to the next appropriate position.

10. Get the current array key key()
key() function returns the key at the current pointer position in input_array. Its form is as follows:
Copy code The code is as follows:

mixed key(array array)

The following example outputs the keys of the $fruits array by iterating through the array and moving the pointer:
Copy the code The code is as follows:

$fruits = array("apple"=>"red", "banana"=>"yellow");
while ($key = key($fruits)) {
printf("%s
", $key);
next($fruits);
}
// apple
// banana

Note that the pointer will not be moved each time key() is called. For this purpose, the next() function needs to be used. The only function of this function is to complete the task of advancing the pointer.

11. Get the current array value current()
The current() function returns the array value at the current pointer position in the array. Its form is as follows:
Copy code The code is as follows:

mixed current(array array)

Modify the previous example below, this time we want to get the array value:
Copy the code The code is as follows:

$fruits = array("apple"=>"red", "banana"=>"yellow");
while ($fruit = current($fruits)) {
printf("%s
", $fruit);
next($fruits);
}
// red
// yellow

12. Get the current array Keys and Values ​​each()
each() function returns the current key/value pair of input_array and advances the pointer one position. Its form is as follows:
Copy code The code is as follows:

array each(array array)

The returned array contains four keys, key 0 and key contain the key name, and key 1 and value contain the corresponding data. If the pointer is at the end of the array before each() is executed, false is returned.
Copy code The 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 conjunction with list() to iterate over an array. This example is similar to the previous example, but the entire array is output in a loop:
Copy the code The code is as follows:

$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 assigning an array to another array will reset the original array pointer, so in the above example if we are looping Internally assigning $fruits to another variable will result in an infinite loop.
This completes array traversal.

Finding, filtering and searching array elements are some common functions of array operations. Here are some related functions.

13. in_array() function
The in_array() function searches for a specific value in an array and returns true if the value is found, otherwise it returns false. Its form is as follows:
Copy code The code is as follows:

boolean in_array(mixed needle,array haystack[,boolean strict]) ;

Look at the following example to find whether the variable apple is already in the array. If it is, output a piece of information:
Copy code The 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 when searching .


14. array_key_exists() function
If a specified key is found in an array, the function array_key_exists() returns true, otherwise it returns false. Its form is as follows:
Copy code The code is as follows:

boolean array_key_exists(mixed key,array array);

The following example will search for apple in the array key, and if found, will output the color of the fruit:
Copy the code The 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 and returns the corresponding key if found, otherwise it returns false. Its form is as follows:
Copy code The code is as follows:

mixed array_search(mixed needle,array haystack[,boolean strict])

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

Copy code The code is as follows:

array array_keys(array array[,mixed search_value])

If the optional parameter search_value is included, only keys matching that value will be returned. The following example will output all arrays found in the $fruit array:
Copy the code The 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
array_values() function returns all the values ​​in an array and automatically provides a numerical index for the returned array. Its form is as follows:
Copy code The code is as follows:

array array_values(array array)

The following example will get the value of each element found in $fruits:
Copy the code The 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 )

Yes Sometimes we need to expand an array, or delete part of the array. PHP provides some functions for expanding and shrinking arrays. These functions provide convenience for programmers who wish to emulate various queue implementations (FIFO, LIFO). As the name suggests, the function names of these functions (push, pop, shift, and unshift) clearly reflect their functions.
PS: The traditional queue is a data structure. The order of deleting elements and adding elements is the same, which is called first-in-first-out, or FIFO. In contrast, a stack is another data structure in which elements are removed in the reverse order in which they were added. This becomes last-in-first-out, or LIFO.


18. Add elements to the head of the array
The array_unshift() function adds elements to the head of the array. All existing numeric keys are modified to reflect their new positions in the array, but associated keys are not affected. Its form is as follows:
Copy code The code is as follows:

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

The following example adds two fruits in front of the $fruits array:
Copy code The 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 of type int, which is a pressure The number of elements in the array after entering the data. You can pass multiple variables as parameters to this function and push multiple variables into the array at the same time. Its form is:
Copy code The code is as follows:

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

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

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

20. Remove value from array header
array_shift() function removes and returns the element found in the array. The result is that if numeric keys are used, all corresponding values ​​are shifted down, whereas arrays using associative keys are not affected. Its form is
Copy code The code is as follows:

mixed array_shift(array array)

The following example deletes the first element apple in the $fruits array:
Copy the code The 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
array_pop() function deletes and returns the array's The last element. Its form is:
Copy code The code is as follows:

mixed array_pop(aray target_array);

The following example deletes the last state from the $states array:
Copy the code The code is as follows:

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325814.htmlTechArticle1. Merge arrays The array_merge() function merges arrays together and returns a combined array. The resulting array starts with the first input array parameter, in the order in which the subsequent array parameters appear...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template