Home >Backend Development >PHP Problem >Can php extract an array?
php can extract the array by: 1. Create a PHP sample file and define an array variable $test; 2. Use the "array_column" function to return the value of the specified column in the given multi-dimensional array; 3. Use the "array_map" function, which applies the callback function to each element in the given array and returns the processed new array; 4. Use the "array_filter" function to filter out the elements that meet the conditions in the given array, and returns a new array.
Operating system for this tutorial: Windows 10 system, php8.1.3 version, Dell G3 computer.
You can use array functions in PHP to extract specific values. The following are several commonly used array functions and how to use them:
1, array_column
This function returns the value of the specified column in a given multi-dimensional array.
//示例数组 $users=[ ['name'=>'Alice','age'=>20,'gender'=>'female'], ['name'=>'Bob','age'=>25,'gender'=>'male'], ['name'=>'Charlie','age'=>30,'gender'=>'male'] ]; //提取'name'列的值 $names=array_column($users,'name'); print_r($names);
The output result is:
Array ( [0]=>Alice [1]=>Bob [2]=>Charlie )
2, array_map
This function applies the callback function to each element in the given array, And return the new processed array.
//示例数组 $numbers=[1,2,3,4,5]; //对每个元素进行求平方操作 $squares=array_map(function($n){ return$n*$n; },$numbers); print_r($squares);
The output result is:
Array ( [0]=>1 [1]=>4 [2]=>9 [3]=>16 [4]=>25 )
3, array_filter
This function filters out the elements that meet the conditions in the given array and returns a new array.
//示例数组 $numbers=[1,2,3,4,5]; //过滤出偶数 $even_numbers=array_filter($numbers,function($n){ return($n%2==0); }); print_r($even_numbers);
The output result is:
Array ( [1]=>2 [3]=>4 )
The above is the detailed content of Can php extract an array?. For more information, please follow other related articles on the PHP Chinese website!