Home > Backend Development > PHP Tutorial > PHP array functions (merge, split, append, find, delete, etc.)

PHP array functions (merge, split, append, find, delete, etc.)

黄舟
Release: 2023-03-05 12:14:02
Original
1727 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:

array array_merge (array array1 array2…,arrayN)
Copy after login

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.

<?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 )  
?>
Copy after login


2. Append array


array_merge_recursive() function is the same as array_merge() , you can combine 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])
Copy after login


The program example 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 )  
?>
Copy after login

Now the key apple points to an array, which consists of two colors An indexed array of values.


3. Connect arrays


array_combine() function will get a new array, which is composed of a group of submitted Composed of keys and corresponding values. Its form is:

array array_combine(array keys,array values)
Copy after login


Note that the two input arrays must be the same size and cannot be empty. The example is 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 )  
?>
Copy after login

4. Split the array array_slice()


array_slice() function will return a part of the array, from It starts at key offset and ends at offset+length. Its form:

array array_slice (array array, int offset[,int length])
Copy after login


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 end of the array Start at the offset position. 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:

<?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 )  
?>
Copy after login

Then we use the next negative length:

<?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 )  
?>
Copy after login

5. Splice arrays array_splice()


array_splice() function will delete all elements from offset to 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]])
Copy after login


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 end of the array. Start at the offset position. 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:

<?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 )  
?>
Copy after login

You can use the optional parameter replacement to specify the array to replace the target part. The example is 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 )  
?>
Copy after login

You can clearly see how to use this function from the program.

6. Intersection of arrays array_intersect()

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

array array_intersect(array array1,array array2[,arrayN…])
Copy after login


The following example will return all fruits that appear in the $fruit1 array and also appear in $fruit2 and $fruit3:

<?php  
$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 )  
?>
Copy after login


The array_intersect() function will consider two elements to be the same only if they are equal and have the same data type.

7. The intersection of associative arrays array_intersect_assoc()


The function array_intersect_assoc() is basically the same as array_intersect(), except that it The keys of the array are also taken into account 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:

array array_intersect_assoc(array array1,array array2[,arrayN…])
Copy after login


The following example returns all keys that appear in the $fruit1 array and also appear in $fruit2 and $fruit3 /Value pair:

<?php  
$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 )  
?>
Copy after login

8. Array difference array_diff()

Function array_diff() returns the value that appears in the first array But the other values ​​are not in the input array. This function is the opposite of array_intersect().

array array_diff(array array1,array array2[,arrayN…])
Copy after login


The example is as follows:

<?php  
$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 )  
?>
Copy after login


9. Difference set of associative array array_diff_assoc( )

函数array_diff_assoc()与array_diff()基本相同,只是它在比较时还考虑了数组的键。因此,只在第一个数组中出现而不再其他输入数组中出现的键/值对才会返回到结果数组中。其形式如下:

array array_diff_assoc(array array1,array array2[,arrayN…])
Copy after login


下面的例子只返回了[yellow] => Banana,因为这个特殊的键/值对出现在$fruit1中,而在$fruit2和$fruit3中都不存在。

<?php  
$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 )  
?>
Copy after login


使用数组的过程中经常要遍历数组。通常需要遍历数组并获得各个键或值(或者同时获得键和值),所以毫不奇怪,PHP为此提供了一些函数来满足需求。许多函数能完成两项任务,不仅能获取当前指针位置的键或值,还能将指针移向下一个适当的位置。

10. 获取当前数组键 key()


key()函数返回input_array中当前指针所在位置的键。其形式如下:

mixed key(array array)
Copy after login


下面的例子通过迭代处理数组并移动指针来输出$fruits数组的键:

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

注意,每次调用key()时不会移动指针。为此需要使用next()函数,这个函数的唯一作用就是完成推进指针的任务。

11. 获取当前数组值 current()

current()函数返回数组中当前指针所在位置的数组值。其形式如下:

mixed current(array array)
Copy after login

下面修改前面的例子,这一次我们要获取数组值:

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

12. 获取当前数组键和值 each()

each()函数返回input_array的当前键/值对,并将指针推进一个位置。其形式如下:

array each(array array)
Copy after login


返回的数组包含四个键,键0和key包含键名,而键1和value包含相应的数据。如果执行each()前指针位于数组末尾,则返回false。

$fruits = array("apple", "banana", "orange", "pear");  
print_r ( each($fruits) );  
  
// Array ( [1] => apple [value] => apple [0] => 0 [key] => 0 )
Copy after login

each() 经常和 list() 结合使用来遍历数组。本例与上例类似,不过循环输出了整个数组:

$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
Copy after login

因为将一个数组赋值给另一个数组时会重置原来的数组指针,因此在上例中如果我们在循环内部将 $fruits 赋给了另一个变量的话将会导致无限循环。

这就完成了数组的遍历。

查找、筛选与搜索数组元素是数组操作的一些常见功能。下面来介绍一下几个相关的函数。


13. in_array()函数

in_array()函数在一个数组汇总搜索一个特定值,如果找到这个值返回true,否则返回false。其形式如下:


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


来看下面的例子,查找变量apple是否已经在数组中,如果在,则输出一段信息:

$fruit = "apple";   
$fruits = array("apple","banana","orange","pear");   
if( in_array($fruit,$fruits) )    
    echo "$fruit 已经在数组中";
Copy after login

第三个参数可选,它强制in_array()在搜索时考虑类型。

14. array_key_exists()函数

如果在一个数组中找到一个指定的键,函数array_key_exists()返回true,否则返回false。其形式如下:

boolean array_key_exists(mixed key,array array);
Copy after login


下面的例子将在数组键中搜索apple,如果找到,将输出这个水果的颜色:

$fruit["apple"] = "red";  
$fruit["banana"] = "yellow";  
$fruit["pear"] = "green";  
if(array_key_exists("apple", $fruit)){  
    printf("apple&#39;s color is %s",$fruit["apple"]);  
}  
  
//apple&#39;s color is red
Copy after login


15. array_search()函数

array_search()函数在一个数组中搜索一个指定的值,如果找到则返回相应的键,否则返回false。其形式如下:

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


下面的例子在$fruits中搜索一个特定的日期(December 7),如果找到,则返回相应州的有关信息:

$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.
Copy after login


16. array_keys()函数

array_keys()函数返回一个数组,其中包含所搜索数组中找到的所有键。其形式如下:

array array_keys(array array[,mixed search_value])
Copy after login


如果包含可选参数search_value,则只会返回与该值匹配的键。下面的例子将输出$fruit数组中找到的所有数组:

$fruits["apple"] = "red";  
$fruits["banana"] = "yellow";  
$fruits["watermelon"]="green";  
$keys = array_keys($fruits);  
print_r($keys);  
  
//Array ( [0] => apple [1] => banana [2] => watermelon )
Copy after login

17. array_values()函数

array_values()函数返回一个数组中的所有值,并自动为返回的数组提供数值索引。其形式如下:

array array_values(array array)
Copy after login


下面的例子将获取$fruits中找到的各元素的值:

$fruits["apple"] = "red";  
$fruits["banana"] = "yellow";  
$fruits["watermelon"]="green";  
$values = array_values($fruits);  
print_r($values);  
  
//Array ( [0] => red [1] => yellow [2] => green )
Copy after login


有时候我们需要扩展一个数组,或者删掉数组的一部分,PHP为扩展和缩小数组提供了一些函数。对于那些希望模仿各种队列实现(FIFO、LIFO)的程序员来说,这些函数可以提供便利。顾名思义,从这些函数的函数名(push、pop、shift和unshift)就清楚地反映出其作用。

PS:传统的队列是一种数据结构,删除元素与加入元素的顺序相同,就称为先进先出,或FIFO。相反,栈是另外一种数据结构,其中删除元素的顺序与加入时的顺序相反,这成为后进先出,或LIFO。


18. 在数组头添加元素

array_unshift()函数在数组头添加元素。所有己有的数值键都会相应地修改,以反映其在数组中的新位置,但是关联键不受影响。其形式如下:

int array_unshift(array array,mixed variable[,mixed variable])
Copy after login

下面这个例子在$fruits数组前面添加了两种水果:

$fruits = array("apple","banana");  
array_unshift($fruits,"orange","pear")  
// $fruits = array("orange","pear","apple","banana");
Copy after login

19. 在数组尾添加元素

array_push()函数的返回值是int型,是压入数据后数组中元素的个数,可以为此函数传递多个变量作为参数,同时向数组压入多个变量。其形式为:

(array array,mixed variable [,mixed variable...])
Copy after login

下面这个例子在$fruits数组中又添加了两个水果:

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

20. 从数组头删除值

array_shift()函数删除并返回数组中找到的元素。其结果是,如果使用的是数值健,则所有相应的值都会下移,而使用关联键的数组不受影响。其形式为

mixed array_shift(array array)
Copy after login

下面的例子删除了$fruits数组中的第一个元素apple:

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

21. 从数组尾删除元素

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

mixed array_pop(aray target_array);
Copy after login

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

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

以上就是PHP数组函数(合并,拆分,追加,查找,删除等)的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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