Home  >  Article  >  Backend Development  >  PHP array operation functions (merge, split, append, search, delete, etc.)_PHP tutorial

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

WBOY
WBOYOriginal
2016-07-13 17:15:44909browse

We know that arrays in PHP are a very important data type in our development. Let me introduce to you the knowledge of PHP arrays (merge, split, append, search, delete, traverse arrays, array sorting, etc.) , students who need to know more can refer to it.

To learn PHP array related knowledge, the main points to learn are the following:
1. Understand the meaning of arrays;
2. Master the methods of declaring one-dimensional arrays and two-dimensional arrays;
3. Master how to output arrays;
4. Master the method of traversing arrays;
5. Understand how to merge arrays;
6. Master the method of converting between strings and arrays;
7. Familiar with how to count the number of array elements;
8. Master the method of sorting arrays;

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:

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.

The code is as follows Copy code
代码如下 复制代码
$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 )
?>
$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
 代码如下 复制代码
$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 )
?>
The array_merge_recursive() function is the same as array_merge(). It can merge two or more arrays 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: array array_merge_recursive(array array1,array array2[…,array arrayN]) The program example is as follows:
The code is as follows Copy code
$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:

array array_combine(array keys,array values)

Note that the two input arrays must be of the same size and cannot be empty. An example 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 array array_slice()

The array_slice() function will return a part of the array, starting from the key offset and ending at offset+length. Its form:

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:

 代码如下 复制代码
$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:

 代码如下 复制代码
$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 will delete all elements starting from offset and ending at offset+length in the array, and return the deleted elements in the form of an array. Its form is:

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. Examples are 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 )
?>

You can use the optional parameter replacement to specify an array to replace the target part. Examples are 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 a key-preserved array consisting only of values ​​that appear in the first array and appear in every other input array. Its form 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:

 代码如下 复制代码
$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 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 also appear in $fruit2 and $fruit3:

 代码如下 复制代码
$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. Difference of array array_diff()

The function array_diff() returns values ​​that appear in the first array but not in other input arrays. This function is the opposite of array_intersect().

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

Examples are 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 of associative array array_diff_assoc()
The function array_diff_assoc() is basically the same as array_diff(), except that it also takes the keys of the array into account when comparing. Therefore, only key/value pairs that appear in the first array but not in the other input arrays are returned in the result array. Its form 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.

The code is as follows Copy code
 代码如下 复制代码
$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 )
?>
$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()

The key() function returns the key at the current pointer position in input_array. Its form 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:

 代码如下 复制代码
$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:

mixed current(array array)

Let’s modify the previous example. This time we want to get 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 advances the pointer one position. Its form 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.

 代码如下 复制代码
$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:

The code is as follows Copy code
$fruits = array("apple", " banana", "orange", "pear");
 代码如下 复制代码
$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
reset($fruits); while (list($key, $val) = each($fruits)) { echo "$key => $val
"; } // 0 => apple // 1 => banana // 2 => orange // 3 => pear

Because assigning one array to another array will reset the original array pointer, in the above example if we assign $fruits to another variable inside the loop, it will cause 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:

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:

 代码如下 复制代码
$fruit = "apple";
$fruits = array("apple","banana","orange","pear");
if( in_array($fruit,$fruits) )
echo "$fruit 已经在数组中";

The third parameter is optional and 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:

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:

 代码如下 复制代码
$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:

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:

 代码如下 复制代码
$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 keys found in the searched array. Its form 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:

The code is as follows Copy code
$fruits["apple"] = "red ";
 代码如下 复制代码
$fruits["apple"] = "red";
$fruits["banana"] = "yellow";
$fruits["watermelon"]="green";
$keys = array_keys($fruits);
print_r($keys);
//Array ( [0] => apple [1] => banana [2] => watermelon )
$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 the values ​​in an array and automatically provides a numerical index for the returned array. Its form is as follows:

array array_values(array array)

The following example will get the value 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 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:

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

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

 代码如下 复制代码
$fruits = array("apple","banana");
array_unshift($fruits,"orange","pear")
// $fruits = array("orange","pear","apple","banana");

19. Add elements to 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 pushing 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:

(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. 从数组头删除值


The 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

mixed array_shift(array array)

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

The code is as follows Copy code
 
 代码如下 复制代码

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

21. 从数组尾删除元素

array_pop()函数删除并返回数组的最后一个元素。其形式为:

mixed array_pop(aray target_array);

下面的例子从$states数组删除了最后的一个州:

 代码如下 复制代码

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

然后上面一些知识我们总结成一个函数

//声明方法一、直接使用array()函数声明数组,下标与数组元素见使用=>连接,下标默认0开始

 代码如下 复制代码


//result: Array([0]=>asp[1]=>php[2]=>jsp)  
 
//指定下标
"asp","2"=>"php","3"=>"jsp");
  print_r($array);
  echo"
";
  echo $array[1];
  echo $array[2];
  echo $array[3];
?>
/*
result:
Array([0]=>asp[1]=>php[2]=>jsp)
aspphpjsp
*/ 
 
//声明方法二、直接为数组赋值声明数组

//result:Array([0]=>asp[1]=>php[2]=>jsp)  
 
//数组的类型如下;
asp[1]=>php[2]=>jsp)
?>  
 
1,"second"=>2,"third"=>3);
echo $newarray["second"];
$newarray["third"]=8;
echo $newarray["third"];
?>
//result:28
一个数组的元素是变量时,这个数组就是一维数组;
一个数组的元素如果是一个一维数组,这个数组就是二维数组;
二维数组,exp:

$str=array(  
  "书籍"=>array("文学","历史","地理"),  
  "体育"=>array("m"=>"足球","n"=>"篮球")  
);
print_r($str);

 

Comprehensive list of array functions

array() creates an array.
array_change_key_case() returns an array whose keys are all uppercase or lowercase.
array_chunk() splits an array into new array chunks.
array_combine() creates a new array by merging two arrays.
array_count_values() is used to count the number of occurrences of all values ​​in an array.
array_diff() returns the difference array of two arrays.
array_diff_assoc() compares the key name and key value and returns the difference array of the two arrays.
array_diff_key() compares key names and returns an array of differences between the two arrays.
array_diff_uassoc() calculates the difference of an array by doing an index check using a user-provided callback function.
array_diff_ukey() uses the callback function to compare the key names to calculate the difference of the array.
array_fill() fills an array with the given values.
array_filter() uses a callback function to filter elements in an array.
array_flip() swaps keys and values ​​in an array.
array_intersect() calculates the intersection of arrays.
array_intersect_assoc() compares key names and key values ​​and returns the intersection array of the two arrays.
array_intersect_key() Computes the intersection of arrays using key name comparison.
array_intersect_uassoc() calculates the intersection of arrays with index checking and compares the indices with a callback function.
array_intersect_ukey() uses a callback function to compare key names to calculate the intersection of arrays.
array_key_exists() checks whether the given key name or index exists in the array.
array_keys() returns all keys in the array.
array_map() applies a callback function to the cells of the given array.
array_merge() Merges one or more arrays into a single array.
array_merge_recursive() Merges one or more arrays recursively.
array_multisort() Sorts multiple arrays or multidimensional arrays.
array_pad() pads an array with values ​​to the specified length.
array_pop() pops (pops) the last element of the array.
array_product() calculates the product of all values ​​in an array.
array_push() pushes one or more cells (elements) to the end of the array (push).
array_rand() randomly selects one or more elements from an array and returns it.
array_reduce() uses a callback function to iteratively reduce an array to a single value.
array_reverse() reverses the order of elements in the original array, creates a new array and returns it.
array_search() searches the array for a given value and returns the corresponding key if successful.
array_shift() deletes the first element in the array and returns the value of the deleted element.
array_slice() removes a segment of value from the array based on conditions and returns it.
array_splice() removes a portion of an array and replaces it with another value.
array_sum() calculates the sum of all values ​​in an array.
array_udiff() uses a callback function to compare data to calculate the difference of arrays.
array_udiff_assoc() calculates the difference of an array with index checking and compares the data using a callback function.
array_udiff_uassoc() calculates the difference set of the array with index checking, using a callback function to compare the data and index.
array_uintersect() calculates the intersection of arrays and uses callback functions to compare data.
array_uintersect_assoc() calculates the intersection of arrays with index checking and compares data using callback functions.
array_uintersect_uassoc() calculates the intersection of arrays with index checking, using a callback function to compare the data and index.
array_unique() removes duplicate values ​​from an array.
array_unshift() Inserts one or more elements at the beginning of the array.
array_values() returns all values ​​in the array.
array_walk() applies a user function to each member of the array.
array_walk_recursive() recursively applies a user function to each member of an array.
arsort() sorts an array in reverse order and maintains index relationships.
asort() sorts an array and maintains index relationships.
compact() creates an array of variable names and their values.
count() counts the number of elements in an array or the number of attributes in an object.
current() returns the current element in the array.
each() returns the current key/value pair in the array and moves the array pointer forward one step.
end() sets the array's internal pointer to the last element.
extract() imports variables from an array into the current symbol table.
in_array() checks whether the specified value exists in the array.
key() gets the key name from an associative array.
krsort() sorts the array in reverse order by key name.
ksort() sorts the array by key name.
list() assigns the values ​​in an array to some variables.
natcasesort() sorts an array in a case-insensitive manner using the "natural sort" algorithm.
natsort() sorts an array using the "natural sorting" algorithm.
next() moves the internal pointer in the array forward one position.
pos() Alias ​​for current().
prev() rolls back the array's internal pointer one bit.
range() creates an array containing elements in the specified range.
reset() sets the array's internal pointer to the first element.
rsort() sorts an array in reverse order.
shuffle() rearranges the elements in the array in random order.
sizeof() Alias ​​for count().
sort() sorts an array.
uasort() sorts the values ​​in an array using a user-defined comparison function and maintains index association.
uksort() sorts the keys in an array using a user-defined comparison function.
usort() sorts the values ​​in an array using a user-defined comparison function

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/628769.htmlTechArticleWe know that arrays in PHP are a very important data type in our development. Let me introduce PHP to you. Array related knowledge learning (merge, split, append, search, delete, traverse...
Statement:
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