0

I am trying to map one array, array1, as key to another array, array2. Basically this:

[
    "array1_val1" => [ 
        "array2_val1"=> "creation_time", 
        "array2_val2"=> "creation_time", 
        ... 
    ],
    ...,
]

This is not the problem, the problem is the method I am trying out. As follows:

$div = array_map(function ($value){
    global $files;
    global $value;
    return array_filter($files, function($k){
        // global $value;
        $ex = explode("_", $k);
        var_dump(substr($ex[0], 0, 5)."    ".$value."   ".__LINE__);
        return substr($ex[0], 0, 5) === $value;
    }, ARRAY_FILTER_USE_KEY);
}, $file_names_g);

Definitions:

  • $file_names_g - is an array that has all distinct values (first 5 letters of the file names of $files values)
  • $files - is an array with filename (key) and creation date (value). The filname starts with same 5 letters in $file_names_g and rest differ depending on date the files are created.

Filename example: ABC_24May2017.bak

Now I want the files that start with the same first 5 letters in $file_names_g with $file_names_g being a key and and array with file name as key and creation date as value, (this is the format of the $files array).

Now the problem is that I cannot figure out how to give $value variable access to the function in array_filter. Mentioning it global doesn't help, I get either an empty value or a null. How can I overcome that or is there any better method?

Regards

echo_salik
  • 842
  • 1
  • 18
  • 35
  • 1
    You can pass a value into a closure using [`use`](https://stackoverflow.com/questions/1065188/in-php-5-3-0-what-is-the-function-use-identifier) – k0pernikus May 24 '17 at 08:33

1 Answers1

3

You can use a variable defined in the outer scope inside a closure function with use:

$value = 'foo';
function($k) use ($value) {
     // you can now access the variable value
}
k0pernikus
  • 60,309
  • 67
  • 216
  • 347
  • 1
    You learn something new everyday! Thanks! but now I have a new problem. Array is mapped to numeric keys, not like I wanted. – echo_salik May 24 '17 at 08:40
  • @echo_salik Please open a new question about that specific question and keep the question only to that one problem. – k0pernikus May 24 '17 at 08:52
  • yeah... i though of that, during which I solved the question. Thanks! – echo_salik May 24 '17 at 08:54
  • @echo_salik you can also ask and answer your own question in one go. (There's a checkbox on the bottom for that.) – k0pernikus May 24 '17 at 09:08
  • my solution was more like... well its ok like that i get what i need. So yeah... not much of a solution xD – echo_salik May 24 '17 at 11:16
  • 1
    @echo_salik Ah ok then :) Just please try to avoid "solved it" comments, as that might come across as a bit insulting to someone having a similar issue as you. If the problem is not even a problem anymore, that's a valid point. – k0pernikus May 24 '17 at 11:17
  • Aye aye Captain! :) – echo_salik May 30 '17 at 06:03