I got this multiple array named $files[]
, which consists of keys and values as below :
[0] => Array
(
[name] => index1.php
[path] => http://localhost/php/gettingstarted/
[number] => 1
)
[1] => Array
(
[name] => index10.php
[path] => http://localhost/php/gettingstarted/
[number] => 2
)
[2] => Array
(
[name] => index11.php
[path] => http://localhost/php/gettingstarted/
[number] => 3
)
I use this code to create a new array consist of 'name' keys only. But it failed
array_filter($files, "is_inarr_key('name')");
function is_inarr_key($array, $key)
{
//TODO : remove every array except those who got the same $key
}
and I get this error:
array_filter() [function.array-filter]: The second argument, 'is_inarr_key('name')', should be a valid callback in C:\xampp\htdocs\php\gettingstarted\index.php on line 15
So my questions are:
array_filter
receive parameter?The array_filter() function filters the values of an array using a callback function. This function passes each value of the input array to the callback function. If the callback function returns true, the current value from input is returned into the result array.
Filtering a PHP array by keys To use the PHP array_filter() function to filter array elements by key instead of value, you can pass the ARRAY_FILTER_USE_KEY flag as the third argument to the function. This would pass the key as the only argument to the provided callback function.
You can create a closure on PHP ≥5.3.
array_filter($files, function($array) use ($key) {
return is_inarr_key($array, $key);
} );
If you are stuck with PHP <5.3, …
You can make $key
a global variable.
function is_inarr_with_global_key($array) {
global $key;
....
}
You can create a class
class KeyFilter {
function KeyFilter($key) { $this->key = $key; }
function is_inarr_key($array) { ... }
}
...
array_filter($files, array(new KeyFilter('name'), 'is_inarr_key'));
You can create 3 different functions
array_filter($files, 'is_inarr_name');
array_filter($files, 'is_inarr_path');
array_filter($files, 'is_inarr_number');
You can write your own array_filter
function my_array_filter($files, $key) {
...
}
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