![]() |
VOOZH | about |
Given an Associative Array, the task is to get all values from the associative array in PHP. To get all the values from an associative array, you can use various approaches such as foreach loop, array_values() function, and array_map() function. In this article, we will explore each approach with detailed explanations and code examples.
Table of Content
The basic approach is to use a foreach loop to iterate over the associative array and access each value.
95 90 96 93 98
The array_values() function returns all the values of an array in a new array and then use foreach loop to access all values of the new array.
95 90 96 93 98
The array_map() function applies a callback function to each value of an array and returns an array with the modified values. After getting the new modified array containing values, we use foreach loop to access all values of the array.
95 90 96 93 98
This approach utilizes the array_reduce() function to accumulate all the values from an associative array into a single new array. array_reduce() iteratively applies a user-defined callback function to each element of the array, carrying the result forward to each subsequent element in a manner that "reduces" the array to a single value, which can be an array itself if designed that way.
Example: In this example, we use array_reduce() to extract all the values of a specific key from an associative array. This is particularly useful when you need to perform additional processing on the values, such as filtering or transforming them before accumulating.
Array ( [0] => 25 [1] => 15 [2] => 100 )
The array_column() function is useful for extracting the values from a single column in an array of arrays or an array of objects. It can also be used to extract all values from an associative array based on the keys.
Example
Array ( [0] => John [1] => 30 [2] => New York )