Home Backend Development PHP Tutorial Personal summary of php array related functions_PHP tutorial

Personal summary of php array related functions_PHP tutorial

Jul 15, 2016 pm 01:21 PM
array php personal for function Split Bundle number array Related


1.array_chunk() splits an array into new array chunks. The number of cells in each array is determined by the size parameter. The last array may have a few fewer elements.
Example
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse","d"=>"Cow");
print_r(array_chunk($a,2));
?>
Output:
Array (
[0] => Array ( [0] => Cat [1] => Dog )
[1] => Array ( [0] => Horse [1] => Cow )
)

This is very similar to the split tool in Linux.
[root@xen187v tmp]$ cat tmp
1
2
3
4
5
6
7
[root@xen187v tmp]$ split -l 2 tmp
[root@xen187v tmp]$ ls
tmp xaa xab xac xad
[root@xen187v tmp]$ cat xaa
1
2
[root@xen187v tmp]$ cat xab
3
4
[root@xen187v tmp]$ cat xac
5
6
[root@xen187v tmp]$ cat xad
7


2.
array_merge() Merges one or more arrays into a single array. [This is a vertical merger]
The array_combine() function creates a new array by merging two arrays, one with keys and the other with keys. [This is a horizontal merger]
If one of the arrays is empty, or the two arrays have different numbers of elements, the function returns false.
Example
$a1=array("a","b","c","d");
$a2=array("Cat","Dog","Horse","Cow");
print_r(array_combine($a1,$a2));
?>

This is very similar to the paste command under Linux.
The word paste means to paste. This command is mainly used to merge the contents of multiple files, which is exactly the opposite of the function of the cut command.


When pasting data from two different sources, you need to classify it first and make sure that the two files have the same number of lines
[root@xen187v tmp]$ cat xaa
1
2
[root@xen187v tmp]$ cat xab
3
4
[root@xen187v tmp]$ paste xaa xab
1 3
2 4
Add one more line to xaa and see what happens
[root@xen187v tmp]$ cat xaa
1
2
3
[root@xen187v tmp]$ paste xaa xab
1 3
2 4
3
Let’s see what happens if we add two more lines to xab
[root@xen187v tmp]$ cat xab
i
i
3
4
[root@xen187v tmp]$ paste xaa xab
1 i
2 i
3 3
4
[root@xen187v tmp]$



3.
array_sum() calculates the sum of all values ​​in an array.
The array_count_values() function is used to count the number of occurrences of all values ​​in an array.
This function returns an array, the key name of its element is the value of the original array, and the key value is the number of times the value appears in the original array.
[Much like uniq -c
[root@xen187v tmp]$ cat xab
i
i
3
4
[root@xen187v tmp]$ uniq -c xab
2 i
1 3
1 4
[root@xen187v tmp]$ uniq -c xab|awk '{print $2" "$1}'
i 2
3 1
4 1
[root@xen187v tmp]$

4.


[Sentiment: It would be great if the names of these array functions were the same as the Linux command names, which would be easier to remember]
5.array_diff() function returns the first array, the array of data items that are not in the subsequent array
6.array_flip() exchanges the keys and values ​​in the array. The function returns a reversed array. If the same value appears multiple times, the last key name will be its value and all other key names will be lost.
If the data type of the value in the original array is not string or integer, the function will report an error.
[This is worth remembering. When processing data, it is easy to encounter key->value flipping situations]
7.array_intersect() calculates the intersection of arrays.

A common question in interviews, use native code to find the intersection of two arrays
function intersectArray($arr1,$arr2)
{
$tmpArr = array();
foreach($arr1 as $v1) $tmpArr[$v1] = 0;
foreach($arr2 as $v2)
{
if(isset($tmpArr[$v2])
{
$tmpArr[$v2] = 1;
}
}
//The intersection with a value of 1 in $tmpArr
$retArr = array();
foreach($tmpArr as $key => $v)
{
if($v == 1) $retArr[] = $key;
}
return $retArr;
}



8.array_keys() returns all key names in the array.
9.
array_rand() randomly selects one or more elements from an array and returns it.
The shuffle() function rearranges the elements in the array in random order
10.
array_reverse() reverses the order of elements in the original array, creates a new array and returns it.
11.
array_search() searches the array for a given value and returns the corresponding key if successful.
12
array_unique() removes duplicate values ​​from an array.
13
arsort() sorts an array in reverse order and maintains index relationships.
asort() sorts an array and maintains index relationships.
krsort() sorts the array in reverse order by key name.
ksort() sorts the array by key name.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477189.htmlTechArticle1.array_chunk() Split an array into new array chunks. The number of cells in each array is determined by the size parameter. The last array may have a few fewer elements. Example ?ph...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Top 10 Digital Virtual Currency Apps Rankings: Top 10 Digital Currency Exchanges in Currency Circle Trading Top 10 Digital Virtual Currency Apps Rankings: Top 10 Digital Currency Exchanges in Currency Circle Trading Apr 22, 2025 pm 03:00 PM

The top ten digital virtual currency apps are: 1. OKX, 2. Binance, 3. gate.io, 4. Coinbase, 5. Kraken, 6. Huobi, 7. KuCoin, 8. Bitfinex, 9. Bitstamp, 10. Poloniex. These exchanges are selected based on factors such as transaction volume, user experience and security, and all provide a variety of digital currency trading services and an efficient trading experience.

What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

H5: Key Improvements in HTML5 H5: Key Improvements in HTML5 Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Composer: The Package Manager for PHP Developers Composer: The Package Manager for PHP Developers May 02, 2025 am 12:23 AM

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json file. 1) parse composer.json to obtain dependency information; 2) parse dependencies to form a dependency tree; 3) download and install dependencies from Packagist to the vendor directory; 4) generate composer.lock file to lock the dependency version to ensure team consistency and project maintainability.

Are all list operations supported by arrays, and vice versa? Why or why not? Are all list operations supported by arrays, and vice versa? Why or why not? Apr 26, 2025 am 12:05 AM

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

See all articles