In PHP, we often need to take out multiple values from an array for processing, such as performing certain calculations, statistics, etc. So, how to remove multiple values from the array? Here, we will introduce several methods to retrieve multiple values from an array in PHP.
The list() function is a very convenient and concise way to take out multiple values from an array. The syntax of this function is as follows:
list($var1, $var2, …) = $array;
Among them, $var1, $var2 are the variable names of the element values to be taken out of the array, and $array is the array to be operated on.
For example, we have an array $colors containing 3 elements, whose element values are "red", "green", and "blue" respectively. Then we can use the list() function to take out this array The first two element values of:
$colors = array("red", "green", "blue"); list($color1, $color2) = $colors; echo "$color1, $color2"; // 输出"red, green"
Array destructuring (array destructuring) is a new feature introduced in PHP 7.1, which can be more convenient Remove multiple values from an array. Compared with using the list() function, array destructuring is more flexible, and the retrieved value can be assigned to any variable.
The syntax of array destructuring is as follows:
[$var1, $var2, …] = $array;
Among them, $var1, $var2 are the variable names of the element values to be taken out of the array, and $array is the array to be operated on.
The following is an example, we use array destructuring to remove the first two element values in the array $colors:
$colors = array("red", "green", "blue"); [$color1, $color2] = $colors; echo "$color1, $color2"; // 输出"red, green"
array_slice($array, $offset, $length);
$numbers = array(1, 2, 3, 4, 5); $firstThreeNumbers = array_slice($numbers, 0, 3); print_r($firstThreeNumbers); // 输出Array([0] => 1,[1] => 2,[2] => 3)
$person = array( "name" => "Tom", "age" => 30, "gender" => "male", ); foreach ($person as $key => $value) { echo "$key: $value\r\n"; }
name: Tom age: 30 gender: male
The above is the detailed content of How to get multiple values from an array in php. For more information, please follow other related articles on the PHP Chinese website!