Home >Backend Development >PHP Tutorial >PHP implements array operations
This article mainly shares with you how to implement array operations in PHP, mainly in the form of text and code. I hope it can help you.
Statistical related
array_sum(array) Statistical array sum
array_product(array) Statistical array product
Example
// 已有字符串2,3,4,5,19,39 $str = '2,3,4,5,19,39'; $arr = explode(',',$str); // 1. array_sum(数组)统计数组的和 echo array_sum($arr); echo '<br/>'; // 2.array_product(数组)统计数组的乘积 echo array_product($arr); echo '<hr/>';
Array first elements&& last element
reset() first element
end() whether the last element
value is in the set
in_array()
Example
$ext = 'jpg'; $allowExts=['jpg','jpeg','gif','png']; var_dump(in_array($ext,$allowExts));
Pointer operation related
array_pop(数组) 删除数组最后一个 array_push(数组,添加元素) 数组末尾添加一个 array_shift(数组) 删除数组第一个 array_unshift(数组,添加元素) 数组开头添加一个
Array to string
implode((separator,)array)
join((separator,) )Array)
Example
// 把逗号与数组拼接成系新字符串$str1 = join(',',range(0,9));echo $str1; 拼接数组 array_merge(arr1,arr2,arr3...) 随机输出key array_rand(数组(,长度)) 交换key和value array_flip()
Example
$arr = ['a','b','c']; $newArr = array_flip($arr); var_dump($newArr); 输出结果: array (size=3) 666 => int 0 'txt' => int 1 'jpg' => int 2 )
Statistics related
array_sum(array) The sum of statistical arrays
array_product(array) Statistical array The product
Example
// 已有字符串2,3,4,5,19,39 $str = '2,3,4,5,19,39'; $arr = explode(',',$str); // 1. array_sum(数组)统计数组的和 echo array_sum($arr); echo '<br/>'; // 2.array_product(数组)统计数组的乘积 echo array_product($arr); echo '<hr/>';
The first element of the array && The last element
reset() The first element
end() The last element
Whether the value is in the collection
in_array()
Example
$ext = 'jpg';
$allowExts=['jpg','jpeg ','gif','png'];
var_dump(in_array($ext,$allowExts));
Pointer operation related
array_pop(array) ##array_push(array, add element) Add an
array_shift(array) at the end of the array Delete the first one in the array
array_unshift(array, add element) Add an
join((separator,)array)
// 把逗号与数组拼接成系新字符串 $str1 = join(',',range(0,9)); echo $str1;Splicing arrayarray_merge( arr1, arr2, arr3...)Randomly output keyarray_rand(array(,length))Exchange key and valuearray_flip( )Example
$arr = ['a','b','c']; $newArr = array_flip($arr); var_dump($newArr); 输出结果: array (size=3) 666 => int 0 'txt' => int 1 'jpg' => int 2 )Related recommendations:
js array operation example analysis
Points to note when operating arrays in JavaScript Basic
PHP array operation development examples and sharing of ideas
The above is the detailed content of PHP implements array operations. For more information, please follow other related articles on the PHP Chinese website!