Processing of php arrays (Array function)

不言
Release: 2023-03-23 21:34:02
Original
8859 people have browsed it

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:

Processing of php arrays (Array function)

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]//如果下标跟前面的重复,则单纯覆盖前面同名下标的值
Copy after login

Associative array

$array = [
    'name' => 'zhaosi',
    'age' => 20,
    'sex' => '女'
];
Copy after login

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' => '男'
    ]
];
Copy after login

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'];
}
Copy after login

Output result

xiaoming
17
男
wanghua
16
女
zhaosi
20
女
zhangsan
22
男
wangli
12
女
zhuhua
14
男
Copy after login

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

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

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

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

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

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

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

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

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

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 是一个引用数组
Copy after login

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

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

Output:

array(
[0]=>array([0]=>1 [1]=>2 [2]=>3)
[1]=>array([0]=>1 [1]=>2 [2]=>3)
)
Copy after login

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!

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