Search code examples
phpphp4

Process an array in a function, with external formatting


I want to pass an array to a function and iterate through it in this function. But I would like to be able to change the way the single entries are displayed.

Suppose I have an array of complicated objects:

$items = array($one, $two, $three);

Right now I do:

$entries = array();
foreach($items as $item) {
    $entries[] = create_li($item["title"], pretty_print($item["date"]));
}
$list = wrap_in_ul($entries);

I would like to do the above in one line:

$list = create_ul($items, $item["title"], pretty_print($item["date"]));

Any chance of doing that as of PHP4? Be creative!


Solution

  • from my understanding, you're looking for an "inject" type iterator with a functional parameter. In php, inject iterator is array_reduce, unfortunately it's broken, so you have to write your own, for example

    function array_inject($ary, $func, $acc) {
     foreach($ary as $item)
      $acc = $func($acc, $item);
     return $acc;
    }
    

    define a callback function that processes each item and returns accumulator value:

    function boldify($list, $item) {
     return $list .= "<strong>$item</strong>";
    }
    

    the rest is easy:

    $items = array('foo', 'bar', 'baz');
    $res = array_inject($items, 'boldify', '');
    print_r($res);