Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible if callback in array_filter receive parameter?

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:

  1. Is it possible to make the call-back function on array_filter receive parameter?
  2. What is the general rule of thumb on how to use callback in any PHP built-in function?
like image 589
justjoe Avatar asked Mar 27 '10 14:03

justjoe


People also ask

What does array_ filter in PHP?

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.

How do you filter an array key?

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.


1 Answers

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) {
  ...
}
like image 111
kennytm Avatar answered Oct 16 '22 19:10

kennytm