Home  >  Article  >  Backend Development  >  PHP returns all the values ​​in the array to form an array

PHP returns all the values ​​in the array to form an array

PHPz
PHPzforward
2024-03-21 09:06:48654browse

php editor Xinyi today introduces you to a common need in PHP: how to extract all the values ​​​​in an array to form a new array. In PHP, we can use the array_values() function to achieve this function. This function will return a new array containing all the values ​​​​of the original array, allowing us to further operate or process the array values. Next, let’s take a look at the specific implementation method!

Use array_values() function

array_values() The function returns an array of all values ​​in an array. It does not preserve the keys of the original array.

$array = ["foo" => "bar", "baz" => "qux"];
$values ​​= array_values($array);
// $values ​​will be ["bar", "qux"]

Use loops

You can use a loop to manually get all the values ​​of the array and add them to a new array.

$array = ["foo" => "bar", "baz" => "qux"];
$values ​​= [];
foreach ($array as $value) {
$values[] = $value;
}
// $values ​​will be ["bar", "qux"]

Use range() function

If the array is a continuous array from 0 to n-1, you can use the range() function to generate an array containing all values.

$array = range(0, 4);
// $array will be [0, 1, 2, 3, 4]

Use array_map() function

array_map() The function can apply a callback function to each value in the array. You can get all the values ​​of an array by using an anonymous function.

$array = ["foo" => "bar", "baz" => "qux"];
$values ​​= array_map(function ($value) {
return $value;
}, $array);
// $values ​​will be ["bar", "qux"]

Return the value of the associative array

If you need to return the value of an associative array, you can use the array_column() function.

$array = ["foo" => "bar", "baz" => "qux"];
$values ​​= array_column($array, "value");
// $values ​​will be ["bar", "qux"]

Processing multi-dimensional arrays

If the array is multi-dimensional, you can use the recursive function to get all values.

function get_array_values($array) {
$values ​​= [];
foreach ($array as $value) {
if (is_array($value)) {
$values ​​= array_merge($values, get_array_values($value));
} else {
$values[] = $value;
}
}
return $values;
}

Performance considerations

Performance considerations should be taken into consideration when choosing the method used to obtain all values ​​of an array. For small arrays, a loop or the array_map() function is usually the fastest option. For large arrays, the array_values() function is usually the most efficient.

The above is the detailed content of PHP returns all the values ​​in the array to form an array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:lsjlt.com. If there is any infringement, please contact admin@php.cn delete