Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.
First use RecursiveIteratorIterator class to flatten the multidimensional array, and then apply array_values() function to get the desired color values in a single array. Here are the references: RecursiveIteratorIterator class. array_values()
The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned. Specified array.
As array values can be other arrays, trees and multidimensional arrays are also possible. And : The key can either be an integer or a string.
Since PHP 5.5, you can use array_column
:
$ids = array_column($users, 'id');
This is the preferred option on any modern project. However, if you must support PHP<5.5, the following alternatives exist:
Since PHP 5.3, you can use array_map
with an anonymous function, like this:
$ids = array_map(function ($ar) {return $ar['id'];}, $users);
Before (Technically PHP 4.0.6+), you must create an anonymous function with create_function
instead:
$ids = array_map(create_function('$ar', 'return $ar["id"];'), $users);
Starting PHP5.5+ you have array_column() available to you, which makes all of the below obsolete.
$ids = array_map(function ($ar) {return $ar['id'];}, $users);
Solution by @phihag will work flawlessly in PHP starting from PHP 5.3.0, if you need support before that, you will need to copy that wp_list_pluck.
In Wordpress there is a function called wp_list_pluck If you're using Wordpress that solves your problem.
PHP < 5.3If you're not using Wordpress, since the code is open source you can copy paste the code in your project (and rename the function to something you prefer, like array_pick). View source here
If id
is the first key in the array, this'll do:
$ids = array_map('current', $users);
You should not necessarily rely on this though. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With