Processing of php arrays (Array function)
Related recommendations: "PHP ARRAY Array Function (Special Topic)"
What is PHP Array?
An array is a collection of data that organizes a series of data to form an operable whole. Arrays in PHP are complex but more flexible than arrays in many other high-level languages.
Array An array is an ordered set of variables, where each value is called an element. Each element is distinguished by a special identifier called a key (also called a subscript).
Each entity in the array contains two items, namely key and value. The corresponding array elements can be obtained by key value. These keys can be numeric keys or association keys. If a variable is a container that stores a single value, then an array is a container that stores multiple values.
PHP arrays are more flexible than arrays in other high-level languages. They not only support index arrays with numbers as keys, but also support associative arrays with strings or a mixture of strings and numbers as keys. In other high-level languages, such as Java or C, only numerically indexed arrays are supported.
The structure of the PHP array is as shown below:
In PHP, there are three array types:
Index array: an array with a numeric index
Associative array: an array with a specified key
Multidimensional array: contains one or more An array of arrays
Recommended video tutorial:
1. "PHP function of array array function video explanation"
2. " Basic PHP Syntax (Jade Girl Heart Sutra Version) "
3. "PHP String Processing (Jade Girl Heart Sutra Version) "
Recommended study manual: "php Complete Self-Study Manual"
PHP Array Use
PHP Array Definition
[1, 5, 1.1, 'abc' true, false] //可以存储任何数据,此时为'默认下标', [2=>1, 5=>5, 3=>1.1, 7=>'abc' 0=>true]//下标可以任意设定(无需顺序,无需连续) [2=>1, 5, 1=>1.1, 'abc' 0=>true]//可以加下标,也可以不加(默认下标),下标分别是:2,3,1,4,0 //默认下标规则:前面已经用过的最大数字下标+1 [2=>1, 'dd'=>5, 1=>1.1, 'abc' 0=>true]//混合下标,同样遵循默认下标规则 [-2=>1, 'dd'=>5, 1.1, 'abc' true]; //负数下标不算在整数下标中,而只当作字符下标 //则最好3项的下标是:0, 1, 2 [2.7=>1, 'dd'=>5, 1=>1.1, 'abc' 0=>true]//浮点数下标为自动转换为整数,且直接抹掉小数 ['2.7' =>1, 'dd'=>5, '11'=>1.1, 'abc' true]//纯数字字符串下标,当作数字看待, //则此时下标为:2, 'dd', 11, 12, 13 [2=>1, 'dd'=>5, true=>1.1, 'abc' false=>true]//布尔值当下标,则true为1,false为0; [2=>1, 'dd'=>5, 2=>1.1, 'abc' true]//如果下标跟前面的重复,则单纯覆盖前面同名下标的值
Associative array
$array = [ 'name' => 'zhaosi', 'age' => 20, 'sex' => '女' ];
Multidimensional array
$array = [ [ 'name' => 'xiaoming', 'age' => 17, 'sex' => '男' ], [ 'name' => 'wanghua', 'age' => 16, 'sex' => '女' ], [ 'name' => 'zhaosi', 'age' => 20, 'sex' => '女' ], [ 'name' => 'zhangsan', 'age' => 22, 'sex' => '男' ], [ 'name' => 'wangli', 'age' => 12, 'sex' => '女' ], [ 'name' => 'zhuhua', 'age' => 14, 'sex' => '男' ] ];
Array traversal
$array = [ [ 'name' => 'xiaoming', 'age' => 17, 'sex' => '男' ], [ 'name' => 'wanghua', 'age' => 16, 'sex' => '女' ], [ 'name' => 'zhaosi', 'age' => 20, 'sex' => '女' ], [ 'name' => 'zhangsan', 'age' => 22, 'sex' => '男' ], [ 'name' => 'wangli', 'age' => 12, 'sex' => '女' ], [ 'name' => 'zhuhua', 'age' => 14, 'sex' => '男' ] ]; foreach ($array as $key => $value) { echo $value['name']; echo $value['age']; echo $value['sex']; }
Output result
xiaoming 17 男 wanghua 16 女 zhaosi 20 女 zhangsan 22 男 wangli 12 女 zhuhua 14 男
Commonly used PHP array functions
1. The count() function is used to count the number of elements in the array or the number of attributes in the object. Number
int count(mixed var[,int mode])
The first parameter is required, passing a calculated array or object. The second parameter is optional and specifies whether the mode of the function recursively calculates the number of elements in the array in the multi-dimensional array. The possible values are 0 or 1. 0 is the default value and multi-dimensional arrays are not detected. If it is 1, multi-dimensional arrays are detected.
Example:
$a = array( "a", "b", "c", "d" ); echo count($a); //输出个数4 $b = array( "a" => array( 1, 2, 3 ) , "b" => array( 4, 5, 6 ) ); echo count($b, 1); //输出 8 echo count($b); //输出 2y([b]=>2 [d]=>4)
2. The array_count_values() function is used to count the number of occurrences of all values in the array. This function has only one parameter
array array_count_values(array input)
parameter Specifies that an array is input and an array is returned. 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.
Example:
$array=array(1,"a",1,"b","a"); $newarray=array_count_values($array); print_r($newarray);//输出array([1]=>2 [a]=>2 [b]=>1)
3 The array_unique() function is used to delete duplicate values in the array and return a new array without duplicate values
array array_unique(array array)
The parameter needs to accept an array. When the values of several elements in the array are equal, only The first element is retained, other elements are deleted, and the key names in the returned new array remain unchanged. array_unique() first sorts the values as strings, then only retains the first encountered key name for each value, and then ignores it. All following key names
Example:
$a=array("a"=>1,"b"=>2,"c"=>1); print_r(array_unique($a));//输出 array([a]=>1 [b]=>2)
4. The array_filter() function uses the callback function to filter the elements in the array and returns the array filtered by the user-defined function
array array_filter(array input [,callback callback])
Parameters: The first parameter is required and requires input of a filtered array. The second parameter is optional. Pass in the user-defined function name in the form of a string. If the custom filter function returns If true, the current value of the operated array will be included in the returned result array, and the result will be formed into a new array. If the original array is an associative array, the key name will remain unchanged.
Example:
function myFun($var) { if ($var % 2 == 0) { return true; } } $array = array( "a" => 1, "b" => 2, "c" => 3, "d" => 4 ); print_r($array, "myFun"); //输出 array([b]=>2 [d]=>4)
5. The array_walk() function applies callback function processing to each element in the array. If successful, it returns true, otherwise it returns false
bool array_walk( array &array,callback funcname [,mixed userdata])
The first parameter is required and requires the input of an array processed by the specified callback function. The second parameter is passed to the user-defined callback function and is used to operate the array passed to the first parameter
Example :
function myFunc1($value, $key) { echo "key=$key value=$value"; } $a = ["a" => "lin1", "b" => "lin2", "c" => "lin3"]; array_walk($a, "myFunc1"); function myFunc2($value, $key, $str) { echo "$key $value"; } array_walk($a, "myFunc2"); function myFunc3($value, $key) { $value = "lin.su"; } array_walk($a, "myFunc3"); print_r($a); //$a 是一个引用数组
6. The array_map() function can process multiple arrays, apply the callback function to the elements of the given array, and return the array after the user-defined function is applied.
array array_map(callback callback,array arr1[,arry ....])
Example:
function myFunc($v1, $v2) { if ($v1 == $v2) { return "same"; } return "different"; } $a = [1, 2, 3]; $b = [1, 4, 3]; print_r(array_map("myFunc", $a, $b)); //输出 array([0]=>same [1]=>difference [2]=>same) print_r(array_map(null, $a, $b));
Output:
array( [0]=>array([0]=>1 [1]=>2 [2]=>3) [1]=>array([0]=>1 [1]=>2 [2]=>3) )
PHP Array Function
Function | Description |
---|---|
array() | Create an array. |
array_change_key_case() | Change all keys in the array to lowercase or uppercase. |
array_chunk() | Split an array into new array chunks. |
array_column() | Returns the value of a single column in the input array. |
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 the array. |
array_diff() | Compare arrays and return the difference set (only compare key values). |
array_diff_assoc() | Compare arrays and return the difference set (compare key names and key values). |
array_diff_key() | Compare arrays and return the difference set (only compare key names). |
array_diff_uassoc() | Compare arrays and return the difference set (compare key names and key values, use user-defined key name comparison function). |
array_diff_ukey() | Compare arrays and return the difference set (only compare key names, use user-defined key name comparison function). |
array_fill() | Fills the array with the given key value. |
array_fill_keys() | Fills an array with the given key value for the specified key name. |
array_filter() | Use the callback function to filter the elements in the array. |
array_flip() | Exchange the keys and values in the array. |
array_intersect() | Compare arrays and return the intersection (only compare key values). |
array_intersect_assoc() | Compare arrays and return intersection (compare key name and key value). |
array_intersect_key() | Compare arrays and return the intersection (only compare key names). |
array_intersect_uassoc() | Compare arrays and return intersection (compare key name and key value, use user-defined key name comparison function). |
array_intersect_ukey() | Compare arrays and return intersection (only compare key names, use user-defined key name comparison function). |
array_key_exists() | Check whether the specified key name exists in the array. |
array_keys() | Returns all key names in the array. |
array_map() | Send each value in the array to the user-defined function and return the new value. |
array_merge() | Merge one or more arrays into one array. |
array_merge_recursive() | Recursively merge one or more arrays. |
array_multisort() | Sort multiple arrays or multidimensional arrays. |
array_pad() | Pad the array to the specified length with values. |
array_pop() | Delete the last element of the array (pop). |
array_product() | Calculate the product of all values in an array. |
array_push() | Insert one or more elements into the end of the array (push). |
array_rand() | Returns one or more random keys in the array. |
array_reduce() | Returns an array as a string by using a user-defined function. |
array_replace() | Replace the value of the first array with the value of the subsequent array. |
array_replace_recursive() | Recursively replace the value of the first array with the value of the subsequent array. |
array_reverse() | Returns an array in reverse order. |
array_search() | Search for the given value in the array and return the key name. |
array_shift() | Deletes the first element in the array and returns the value of the deleted element. |
array_slice() | Returns the selected part of the array. |
array_splice() | Removes and replaces the specified elements in the array. |
array_sum() | Returns the sum of the values in the array. |
array_udiff() | Compare arrays and return the difference set (only compare values, using a user-defined key comparison function). |
array_udiff_assoc() | Compare arrays and return difference sets (compare keys and values, use built-in functions to compare key names, use user-defined functions to compare key values) . |
array_udiff_uassoc() | Compare arrays and return the difference set (compare keys and values, using two user-defined key name comparison functions). |
array_uintersect() | Compares arrays and returns the intersection (only compares values, using a user-defined key comparison function). |
array_uintersect_assoc() | Compare arrays and return the intersection (compare keys and values, use built-in functions to compare key names, use user-defined functions to compare key values). |
array_uintersect_uassoc() | Compare arrays and return the intersection (compare keys and values, using two user-defined key name comparison functions). |
array_unique() | Remove duplicate values from the array. |
array_unshift() | Insert one or more elements at the beginning of the array. |
array_values() | Returns all the values in the array. |
array_walk() | Apply a user function to each member of the array. |
array_walk_recursive() | Applies a user function recursively to each member of an array. |
arsort() | Sort the associative array in descending order by key value. |
asort() | Sort the associative array in ascending order by key value. |
compact() | Creates an array containing variable names and their values. |
count() | Returns the number of elements in the array. |
current() | Returns the current element in the array. |
each() | Returns the current key/value pair in the array. |
end() | Point the internal pointer of the array to the last element. |
extract() | Import variables from the array into the current symbol table. |
in_array() | Checks whether the specified value exists in the array. |
key() | Get the key name from the associative array. |
krsort() | Sort the array in reverse order by key name. |
ksort() | Sort the array by key name. |
list() | Assign the values in the array to some variables. |
natcasesort() | Use the "natural sorting" algorithm to sort the array in a case-insensitive manner. |
natsort() | Sort the array using the "natural sorting" algorithm. |
next() | Move the internal pointer in the array forward one position. |
pos() | Alias for current(). |
prev() | Rewind the internal pointer of the array by one bit. |
range() | Creates an array containing cells in the specified range. |
reset() | Point the internal pointer of the array to the first element. |
rsort() | Sort the array in reverse order. |
shuffle() | Shuffle the array. |
sizeof() | An alias for count(). |
sort() | Sort the array. |
uasort() | Use a user-defined comparison function to sort the key values in the array. |
uksort() | Use a user-defined comparison function to sort the key names in the array. |
usort() | Sort the array using a user-defined comparison function. |
The above is the detailed content of Processing of php arrays (Array function). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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

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,

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

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

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