Is there an array_map() for methods?

Hi, I’ve got this code which does work.

It runs HTMLPurifier on the last values in a multi-array which is written to an ini fiile using PEAR::Config_Lite.

I spoofed a Purifier class in order to explain my question.

Is there anything similar to array_map that I could run on a class method instead of this nested foreach loop, which I really don’t like looking at.


// incoming
$test['en']['this'] = 'that';
$test['en']['the'] = 'other';
$test['fr']['this'] = 'ceci';
$test['fr']['the'] = 'cela';

class Purifier{  // spoofing the real class
  function purify($x){
  return $x . '!';
  }
}

$purifier = new Purifier ;

$config = array();

    foreach($test as $lang=>$array){
        $r = array();
        foreach($array as $k=>$v){  // buerk!
        $r[$k]  = $purifier->purify($v);
        }
        $config[$lang] = $r;
    }

die(var_export($config));

Or is there really no other way?

I think if it were a static method, yes, you could. But with it being instantiated, that may prove to be much harder. Of course, before I posted, this I did a quick search and proved myself wrong :slight_smile:

array_map(array($instance, 'method_name'), $ar)

Have you tried array_walk_recursive?


<?php
$test['en']['this'] = 'that';
$test['en']['the'] = 'other';
$test['fr']['this'] = 'ceci';
$test['fr']['the'] = 'cela';

array_walk_recursive($test, function(&$item, &$key) use ($purifier) {
	if (!is_array($item)) $item = $purifier->purify($item); 
});

print_r($test);



$config = array();
    foreach($test as $l=>$array)
      $config[$l]  = array_map(array($purifier, 'purify'), $array);

Duh, search for your question title before posting … who’d have thought it …

Nice one thanks both.

EDIT, gaaargh … now I spot it mentioned in the comments of the manual page.

Still, on the plus side I did at least spot that it could be improved and had a hunch what the solution ought to be – so I must be improving, I just need to clean my glasses.

Off Topic:

Just a quick note to say that is_array() will never be true. array_walk_recursive() does not send arrays to the callback function.

Off Topic:

Aha, thanks I did wonder about that when I posted it and having read the manual again it does make it clear, although I didn’t spot it at the time! A poor case of RTFM.