Home Backend Development PHP Tutorial Summary of common array functions in PHP (with code examples)

Summary of common array functions in PHP (with code examples)

Sep 24, 2021 pm 03:05 PM
php

1. Some basic operation functions on keys and values ​​of arrays
1. Get all the keys or values ​​of the array:array_keys() array_values()

$arr_keys = array_keys($array);$arr_values = array_values($arr);
Copy after login

2. Exchange the positions of keys and values ​​in the array. If the previous one is repeated, it will be overwritten by the later one: array_flip()

$arr2 = array_flip($arr);
Copy after login

3. The given value Whether it is in the array: in_array(value,array)

$bool = in_array('hello',$arr);
Copy after login

4. Search for a value in the array, and return its key if it is there, or FALSE if it is not: array_search ()

$bool = array_search('hello',$arr);
Copy after login

5. Whether the given key exists in the array:isset(array[key])andarray_key_exists(key,array)

$bool = array_key_exists('a',$arr);
Copy after login

6. Get the number of array elements: count(array,mode). When mode is 1, it means recursively counting the array. The default is 0. Alias ​​sizeof()

$n = count($arr);  //等价于:$n = sizeof($arr);
Copy after login

7. Change the key name in the array to all lowercase or uppercase: array_change_key_case(array,case). There are two commonly used variables in case: CASE_UPPER or CASE_LOWER (default value), which is all lowercase by default

$lowarr = array_change_key_case($arr,CASE_LOWER);
Copy after login

8. Count the number of occurrences of all values ​​in the array: array_count_value(array). Return an array, the key is the value of the original array, the value is the number of times this element appears in the original array

$arr_count = array_count_values($arr);
Copy after login

9. Get the first or last key name of the array: array_key_first(array), array_key_last(array)

$key = array_key_first($arr)
Copy after login

10. Pop the last element of the array:

$last = array_pop($array);
Copy after login

Push one or more cells to the end of the array or the beginning of the array , and returns the number of new arrays:

$new_array = array_push($array,$value1,$value2,...);$new_array = array_unshift($array,$value1,$value2,...);
Copy after login

11. Reverse the array: array_reverse(array)

$reverse = array_reverse($arr)
Copy after login

12. Sum all the values ​​in the array or Find the product:

$sum = array_sum($array);$product = array_product($array);
Copy after login

13. Remove duplicate values ​​from the array:

array_unique($array,,SORT_STRING);sort_falgs参数用于修改排序行为:SORT_NUMERIC - 按照数字形式比较、SORT_STRING - 按照字符串形式比较
Copy after login

14. Shuffle the array: shuffle(array)

$bool = shuffle($arr);
Copy after login

15 . Randomly obtain one or more key names from the array: array_rand(array,num=1), and return an array containing random key names.

2. Summary of some operation functions for creating and splitting arrays
1. Split an array into multiple arrays:array_chunk(array,size,preserve_keys)
Parameters:
size: Specify the number of elements in each array
preserve_keys: Specify whether to retain the original key name, the default is false.
The function returns a two-dimensional array

$myarr = array_chunk($arr,2)
Copy after login

2. Create an array, using the value of one array as its key name and the value of another array as its value: array_combine(keys,values)

$arr_1 = ['A','B','C'];$arr_2 = ['a','b','c'];$arr_3 = array_combine($arr_1,$arr_2);
Copy after login

3. Fill the array with the specified keys and values: array_fill_keys(keys,value)

$keys = array('foo', 5, 10, 'bar');$a = array_fill_keys($keys, 'banana');
Copy after login

4. Fill the array with the given values: array_fill(start_index,num,value)
Parameters:
start_index: The first index of the array
num: The number of inserted elements The quantity, that is, the length of the array, must be a non-negative number
value: the value used to fill

$arr = array_fill(0,10,'myname');
Copy after login

5. Merge one or more arrays: array_merge(array1, array2...)
When the key names are the same, if the key name is a character, it will be overwritten, but the numeric key name will not be overwritten, but will be appended to the end

$a = array_merge($arr_1,$arr_2);
Copy after login

6. Recursive Merge one or more arrays: array_merge_recursive(array_1,array_2,...)
If the arrays have the same array key name, the latter value will not overwrite the original value, but will be appended to Next.

7. Fill a value into the array with the specified length:array_pad(array,size,value)
Parameters:
size: The length of the array after filling. If it is positive, it will be filled to the right side of the array. If it is negative, it will be filled to the left side of the array.
value: The value used to fill

8. From the array Take a section out of: array_slice(array,offset,length,preserve_keys)
Parameters:
offset: The starting offset, either positive or negative
length: The obtained length, a positive number indicates the number of elements obtained, a negative number indicates the distance from the end of the array
preserve_keys: Whether to retain the original key name

10. Remove a certain part of the array and replace it with other values: array_splice(array,offset,length,replacement_array)
Parameters:
replacement_array: The removed unit is The unit replacement in this array

11. Use variables to create an array:compact(var1,var2,...), the variable name is the key name, and the variable value is the value of the element

12. Export variables from the array: extract(array), the key is the variable name, and the value is the value of the variable

13. Assign the value of the array to the variable: list(var1,var2,...)

list($drink, , $power) = array('coffee', 'brown', 'caffeine');
Copy after login

14. Create an array based on the range, containing the specified elements:range(start,end,step)

range(0,8,2) ==> [0,2,4,6,8]
Copy after login

三、数组排序基本函数名为 sort
可以添加其他拓展:r表示逆向排序,k表示对键名进行排序,a表示保持索引关系,u表示用自定义的函数进行比较 1.详细介绍sort函数的情况,其他的函数类似

/*bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )SORT_REGULAR参数可以用以下值改变排序的行为:SORT_REGULAR - 正常比较单元(不改变类型)SORT_NUMERIC - 单元被作为数字来比较SORT_STRING - 单元被作为字符串来比较SORT_LOCALE_STRING - 根据当前的区域(locale)设置来把单元当作字符串比较,可以用 setlocale() 来改变。SORT_NATURAL - 和 natsort() 类似对每个单元以“自然的顺序”对字符串进行排序。 PHP 5.4.0 中新增的。SORT_FLAG_CASE - 能够与 SORT_STRING 或 SORT_NATURAL 合并(OR 位运算),不区分大小写排序字符串。 */
Copy after login

排序函数分类大致如下:

2.sort()、rsort():对值进行升序和降序的排序3.ksort()、krsort():对键名进行升序和降序的排序4.asort()、arsort():保持索引关系的同时,对值进行升序和降序的排序5.usort()、uksort()、uasort():使用自定义的排序函数,进行按值的升序排序、按键名的升序排序、保持索引关系的升序排序6.natsort():使用自然排序算法对数组进行排序7.natcasesort():使用自然排序算法对数组进行不区分大小写字母的排序
Copy after login

四、数组运算
数组差集的计算 u表示用自定义的回调函数,diff表示用数据做差集,assoc表示用索引做差集

1.计算数组的差集:array_diff(array1,array2,...) 对比array1和其他数组,返回在array1中但不在其他数组中的值。返回一个数组,但是键名不保留

2.用回调函数比较数据来计算数组的差集:array_udiff(arr1,arr2,...,value_cpmpare_func)
使用用户自定义的函数进行数据比较,而不是内置的函数。

3.使用键名比较计算数组的差集:array_diff_key(array1,array2,...)
使用键名而不是值来进行差集计算

4.用回调函数对键名比较计算数组的差集:array_diff_ukey(arr1,arr2,...,key_compare_func)

5.带索引检查计算数组的差集:array_diff_assoc(array1,array2,..)
同时使用键名和值来进行差集计算

6.带索引检查计算数组的差集,用回调函数比较索引:array_diff_uassoc(arr1,arr2,...,key_compare_func)
key_compare_func:用户自定义的用于比较键名的函数。

7.带索引检查计算数组的差集,用回调函数比较数据:array_udiff_assoc(arr1,arr2,...,value_cpmpare_func)
value_cpmpare_func:用户自定义的用于比较数据的函数

8.用回调函数比较数据和索引,计算数组的差集:array_udiff_uassoc(arr1,arr2,...,value_cpmpare_func,key_compare_func)

数组交集的计算 同差集一样,也有8个函数:

array_intersect()                     使用数据进行交集比较array_uintersect()                    使用数据进行交集比较,但是自定义函数比较array_intersect_key()                 使用键名进行交集比较array_intersect_ukey()                使用键名进行交比较,但是自定义函数比较array_intersect_assoc()               同时使用数据和键名array_intersect_uassoc()              同时使用数据和键名,但是键名使用自定义函数比较array_uintersect_assoc()              同时使用数据和键名,但是数据使用自定义函数比较array_uintersect_uassoc()             同时使用数据和键名,都使用自定义函数
Copy after login

推荐学习:《PHP视频教程

The above is the detailed content of Summary of common array functions in PHP (with code examples). For more information, please follow other related articles on the PHP Chinese website!

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

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles