当前位置:网站首页>PHP array functions (merge, split, append, find, delete, etc.)
PHP array functions (merge, split, append, find, delete, etc.)
2022-07-01 09:24:00 【Does fried dough twist hurt】
- Merge array
array_merge() Function to merge arrays together , Returns an associative array . The resulting array starts with the first input array parameter , Add the following array parameters in the order they appear . In the form of :
array array_merge (array array1 array2…,arrayN)
This function combines the cells of one or more arrays , The values in an array are appended to the back of the previous array . Returns an array as a result .
If the input array has the same string key name , Then the value after the key name will overwrite the previous value . However , If the array contains a numeric key name , The latter value will not overwrite the original value , It's attached to the back .
If only one array is given and the array is digitally indexed , The key name is re indexed in a continuous 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 ) ?>- Append array
array_merge_recursive() Function and array_merge() identical , You can combine two or more arrays , Form a joint array . The difference between the two is , When a key in an input array already exists in the result array, the function will take different processing methods .array_merge() Will overwrite the previously existing keys / It's worth it , Replace with the key in the current input array / It's worth it , and array_merge_recursive() Will merge the two values together , Form a new array , And take the original key as the array name . There is also an array merge form , Is to recursively append an array . In the form of :
array array_merge_recursive(array array1,array array2[…,array arrayN])
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 ) ?>Now key apple Point to an array , This array is an indexed array of two color values .
- Linked array
array_combine() Function will get a new array , It consists of a set of submitted keys and corresponding values . In the form of :
array array_combine(array keys,array values)
Be careful , Both input arrays must be the same size , Can't be empty . Examples are 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 ) ?>- split array array_slice()
array_slice() Function will return part of the array , From the key offset Start , To offset+length End of position . Its form :
array array_slice (array array, int offset[,int length])
offset When it is a positive value , The split will start from the beginning of the array offset Position start ; If offset negative , From the end of the array offset Position start . If optional parameters are omitted length, Then the split will start from offset Start , Until the last element of the array . If given length And it's a positive number , Will be at the beginning of the array offset+length End of position . contrary , If given length And negative , Then... From the beginning of the array count(input_array)-|length| End of position . 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 ) ?>Then we use the 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 ) ?>- Join array array_splice()
array_splice() The function deletes from the array offset Start to offset+length All the elements of the end , And return the deleted element in the form of array . In the form of :
array array_splice ( array array , int offset[,length[,array replacement]])
offset When it is a positive value , Then the join will start from... From the beginning of the array offset Position start ,offset When it's negative , The join will start at... From the end of the array offset Position start . If you ignore the optional length Parameters , From offset All elements from the beginning of the position to the end of the array will be deleted . If given length And it's positive , The join will be at... From the beginning of the array offset + leng th End of position . contrary , If given length And it's negative , The combination will be at the beginning of the array count(input_array)-length End of position for . 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 ) ?>You can use optional parameters replacement To specify an array that replaces 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")); 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 .
- The intersection of arrays array_intersect()
array_intersect() The function returns an array of keys , This array consists only of the values that appear in the first array and in every other input array . Its form is as follows :
array array_intersect(array array1,array array2[,arrayN…])
The following example will return to f r u i t 1 Count Group in Out present Of And stay fruit1 Appears in the array and in fruit1 Count Group in Out present Of And stay fruit2 and $fruit3 All the fruits that also appear in :
<?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 ) ?>Only when two elements are equal and have the same data type ,array_intersect() Functions will think they are the same .
- Intersection of associative arrays array_intersect_assoc()
function array_intersect_assoc() And array_intersect() Basically the same , But he also considered the keys of the array in the comparison . therefore , Appears only in the first array , And in all other input arrays / Value pairs are returned to the result array .
Form the following :
array array_intersect_assoc(array array1,array array2[,arrayN…])
The following example returns what appears in f r u i t 1 Count Group in , also Same as when Out present stay fruit1 Array , It also appears in fruit1 Count Group in , also Same as when Out present stay fruit2 And $fruit3 All the keys in / It's worth it :
<?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 ) ?>- Difference set of array array_diff()
function array_diff() Returns a value that appears in the first array but not in other input arrays . This function is associated with array_intersect() contrary .
array array_diff(array array1,array array2[,arrayN…])
Examples are 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 ) ?>- The difference set of associative arrays array_diff_assoc()
function array_diff_assoc() And array_diff() Basically the same , But it also considers the keys of the array when comparing . therefore , Keys that appear only in the first array and no longer appear in other input arrays / Value pairs are returned to 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 of this special key / Value pairs appear in f r u i t 1 in , and stay fruit1 in , And in the fruit1 in , and stay fruit2 and $fruit3 None of them exist .
<?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 ) ?>In the process of using an array, you often have to traverse the array . You usually need to traverse the array and get each key or value ( Or get both keys and values ), So it's no surprise ,PHP For this purpose, some functions are provided to meet the requirements . Many functions can accomplish two tasks , It can not only get the key or value of the current pointer position , It can also move the pointer to the next appropriate position .
- Gets the current array key key()
key() The function returns input_array The key where the current pointer is located in the . Its form is as follows :
mixed key(array array)
The following example iterates through the array and moves the pointer to output $fruits The key of the array :
f r u i t s = a r r a y ( " a p p l e " = > " r e d " , " b a n a n a " = > " y e l l o w " ) ; w h i l e ( fruits = array("apple"=>"red", "banana"=>"yellow"); while ( fruits=array("apple"=>"red","banana"=>"yellow");while(key = key($fruits)) {
printf("%s
", k e y ) ; n e x t ( key); next( key);next(fruits);
}
// apple
// banana
Be careful , Every time you call key() Does not move the pointer . To do this, you need to use next() function , The only purpose of this function is to complete the task of pushing the pointer .
- Get the current array value current()
current() Function returns the array value of the current pointer in the array . Its form is as follows :
mixed current(array array)
Let's modify the previous example , This time we're going to get the array value :
f r u i t s = a r r a y ( " a p p l e " = > " r e d " , " b a n a n a " = > " y e l l o w " ) ; w h i l e ( fruits = array("apple"=>"red", "banana"=>"yellow"); while ( fruits=array("apple"=>"red","banana"=>"yellow");while(fruit = current($fruits)) {
printf("%s
", f r u i t ) ; n e x t ( fruit); next( fruit);next(fruits);
}
// red
// yellow
- Get the current array key and value each()
each() The function returns input_array Current key of / It's worth it , And push the pointer to a position . Its form is as follows :
array each(array array)
The returned array contains four keys , key 0 and key Contains the key name , And the key 1 and value Contains the corresponding data . If you execute each() The front pointer is at the end of the array , Then return to false.
f r u i t s = a r r a y ( " a p p l e " , " b a n a n a " , " o r a n g e " , " p e a r " ) ; p r i n t r ( e a c h ( fruits = array("apple", "banana", "orange", "pear"); print_r ( each( fruits=array("apple","banana","orange","pear");printr(each(fruits) );
// Array ( [1] => apple [value] => apple [0] => 0 [key] => 0 )
each() Often with list() Used in conjunction with to traverse an array . This example is similar to the previous example , But the loop outputs the entire array :
f r u i t s = a r r a y ( " a p p l e " , " b a n a n a " , " o r a n g e " , " p e a r " ) ; r e s e t ( fruits = array("apple", "banana", "orange", "pear"); reset( fruits=array("apple","banana","orange","pear");reset(fruits);
while (list($key, v a l ) = e a c h ( val) = each( 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 example above, if we were inside the loop, we would $fruits If you assign another variable, it will result in an infinite loop .
This completes the traversal of the array .
lookup 、 Filtering and searching array elements are some common functions of array operations . Let's introduce a few related functions .
- in_array() function
in_array() Function to search for a specific value in an array , If you find this value, return true, Otherwise return to false. Its form is as follows :
boolean in_array(mixed needle,array haystack[,boolean strict]);
Let's look at the following example , Find variables apple Whether it is already in the array , If in , Then a message is output :
$fruit = “apple”;
f r u i t s = a r r a y ( " a p p l e " , " b a n a n a " , " o r a n g e " , " p e a r " ) ; i f ( i n a r r a y ( fruits = array("apple","banana","orange","pear"); if( in_array( fruits=array("apple","banana","orange","pear");if(inarray(fruit, f r u i t s ) ) e c h o " fruits) ) echo " fruits))echo"fruit Already in the array ";
The third parameter is optional , It forces in_array() Consider types when searching .
- array_key_exists() function
If a specified key is found in an array , function array_key_exists() return true, Otherwise return to false. Its form is as follows :
boolean array_key_exists(mixed key,array array);
The following example will search in the array key apple, If you find , The color of this fruit will be output :
$fruit[“apple”] = “red”;
$fruit[“banana”] = “yellow”;
$fruit[“pear”] = “green”;
if(array_key_exists(“apple”, KaTeX parse error: Expected '}', got 'EOF' at end of input: …s color is %s",fruit[“apple”]);
}
//apple’s color is red
- array_search() function
array_search() Function searches an array for a specified value , If found, the corresponding key is returned , Otherwise return to false. Its form is as follows :
mixed array_search(mixed needle,array haystack[,boolean strict])
The following example is in $fruits Search for a specific date in (December 7), If you find , Then return the relevant information of the corresponding state :
$fruits[“apple”] = “red”;
$fruits[“banana”] = “yellow”;
$fruits[“watermelon”]=“green”;
$founded = array_search(“green”, f r u i t s ) ; i f ( fruits); if( fruits);if(founded)
printf("%s was founded on %s.",$founded, f r u i t s [ fruits[ fruits[founded]);
//watermelon was founded on green.
- array_keys() function
array_keys() Function returns an array , It contains all the keys found in the searched array . Its form is as follows :
array array_keys(array array[,mixed search_value])
If optional parameters are included search_value, Then only the key matching the value will be returned . The following example will output $fruit All arrays found in the array :
$fruits[“apple”] = “red”;
$fruits[“banana”] = “yellow”;
$fruits[“watermelon”]=“green”;
k e y s = a r r a y k e y s ( keys = array_keys( keys=arraykeys(fruits);
print_r($keys);
//Array ( [0] => apple [1] => banana [2] => watermelon )
- array_values() function
array_values() Function returns all the values in an array , And automatically provide a numerical index for the returned array . Its form is as follows :
array array_values(array array)
The following example will get $fruits The value of each element found in :
$fruits[“apple”] = “red”;
$fruits[“banana”] = “yellow”;
$fruits[“watermelon”]=“green”;
v a l u e s = a r r a y v a l u e s ( values = array_values( values=arrayvalues(fruits);
print_r($values);
//Array ( [0] => red [1] => yellow [2] => green )
Sometimes we need to extend an array , Or delete part of the array ,PHP Some functions are provided for expanding and shrinking arrays . For those who want to emulate various queue implementations (FIFO、LIFO) For programmers , These functions can provide convenience . seeing the name of a thing one thinks of its function , From the function names of these functions (push、pop、shift and unshift) It clearly reflects its role .
PS: The traditional queue is a data structure , Deleting elements is in the same order as adding elements , It is called first in first out , or FIFO. contrary , Stack is another data structure , The order in which the elements are deleted is the reverse of the order in which they were added , This becomes LIFO , or LIFO.
- Add element to array header
array_unshift() Function to add an element to the array header . All existing numeric keys will be modified accordingly , To reflect its new position in the array , But the correlation key is not affected . Its form is as follows :
int array_unshift(array array,mixed variable[,mixed variable])
The following example is in $fruits Two kinds of fruit are added in front of the array :
f r u i t s = a r r a y ( " a p p l e " , " b a n a n a " ) ; a r r a y u n s h i f t ( fruits = array("apple","banana"); array_unshift( fruits=array("apple","banana");arrayunshift(fruits,“orange”,“pear”)
// $fruits = array(“orange”,“pear”,“apple”,“banana”);
- Add element at the end of array
array_push() The return value of the function is int type , Is the number of elements in the array after pressing data , You can pass multiple variables as arguments to this function , Push multiple variables into the array at the same time . In the form of :
(array array,mixed variable [,mixed variable…])
The following example is in $fruits Two more fruits are added to the array :
f r u i t s = a r r a y ( " a p p l e " , " b a n a n a " ) ; a r r a y p u s h ( fruits = array("apple","banana"); array_push( fruits=array("apple","banana");arraypush(fruits,“orange”,“pear”)
//$fruits = array(“apple”,“banana”,“orange”,“pear”)
- Delete the value from the array header
array_shift() Function to delete and return the elements found in the array . As a result, , If a numeric key is used , Then all corresponding values will move down , Arrays that use associative keys are not affected . In the form of
mixed array_shift(array array)
The following example deleted $fruits First element in array apple:
$fruits = array(“apple”,“banana”,“orange”,“pear”);
f r u i t = a r r a y s h i f t ( fruit = array_shift( fruit=arrayshift(fruits);
// $fruits = array(“banana”,“orange”,“pear”)
// $fruit = “apple”;
- Delete elements from the end of the array
array_pop() The function deletes and returns the last element of the array . In the form of :
mixed array_pop(aray target_array);
The following example is from $states Array deletes the last state :
$fruits = array(“apple”,“banana”,“orange”,“pear”);
f r u i t = a r r a y p o p ( fruit = array_pop( fruit=arraypop(fruits);
// f r u i t s = a r r a y ( " a p p l e " , " b a n a n a " , " o r a n g e " ) ; / / fruits = array("apple","banana","orange"); // fruits=array("apple","banana","orange");//fruit = “pear”;
边栏推荐
- js重写自己的函数
- [interview brush 101] linked list
- NiO zero copy
- An overview of the design of royalties and service fees of mainstream NFT market platforms
- Football and basketball game score live broadcast platform source code /app development and construction project
- js函数arguments对象
- Principles of Microcomputer - internal and external structure of microprocessor
- Differences between JS valueof and toString
- 【ESP 保姆级教程 预告】疯狂Node.js服务器篇 ——案例:ESP8266 + DS18B20温度传感器 +NodeJs本地服务+ MySQL数据库
- Record a redis timeout
猜你喜欢

Which method is good for the management of fixed assets of small and medium-sized enterprises?

Network counting 01 physical layer

2.2 【pytorch】torchvision. transforms

JS scope chain and closure

2022.02.15_ Daily question leetcode six hundred and ninety

How to realize the usage of connecting multiple databases in idel

Simple load balancing with Nacos
![[interview brush 101] linked list](/img/52/d159bc66c0dbc44c1282a96cf6b2fd.png)
[interview brush 101] linked list

Error org apache. catalina. core. StandardContext. FilterStart start filter exception

PR training notes
随机推荐
Pain points and solutions of fixed assets management of group companies
phpexcel 里 获取某一列的列表 获取某一列的字母
Closure implementation iterator effect
MySQL optimization
队列的实现和应用
JS use toString to distinguish between object and array
ES6 const essence and completely immutable implementation (object.free)
How to realize the usage of connecting multiple databases in idel
[ESP nanny level tutorial preview] crazy node JS server - Case: esp8266 + DS18B20 temperature sensor +nodejs local service + MySQL database
2.4 activation function
NoSQL数据库的安装和使用
SDN_简单总结
Principles of Microcomputer - Introduction
【pytorch】softmax函数
【ESP 保姆级教程】疯狂毕设篇 —— 案例:基于阿里云、小程序、Arduino的WS2812灯控系统
A 419 error occurred in the laravel postman submission form. July 6th, 2020 diary.
【ESP 保姆级教程 预告】疯狂Node.js服务器篇 ——案例:ESP8266 + MQ系列 + NodeJs本地服务 + MySql存储
Mysql8.0 learning record 17 -create table
js函数arguments对象
Design and manufacture of simple digital display electronic scale