jterry jterry - 2 months ago 26
PHP Question

Using a callback in implode()

I have a multidimensional array, e.g.:

$values = array(
'one' => array(
'title' => 'Title One',
'uri' => 'http://example.com/one',
),
'two' => array(
'title' => 'Title Two',
'uri' => 'http://example.com/two',
),
);


...and I'd like to parse through that with a closure in my
implode
function, à la:

$final_string = implode(' | ', function($values) {
$return = array();

foreach($values as $value)
$return[] = '<a href="' . $value['uri'] . '">' . $value['title'] . '</a>';

return $return;
});


However, this usage yields an
Invalid arguments passed
error. Is there syntax that I'm missing which will make this use of closures possible? I'm using PHP v5.3.16.

Answer

Ashwin's answer is correct. Here's why:

When you pass the closure directly to the implode method - which explicitly wants a second argument of type array, it essentially checks the instanceof - hence the invalid argument. The implode function does not expect mixed and doesn't know to execute the closure.

When you first assign that function to a variable, it causes PHP to first evaluate that variable and it ends up passing the returned value from the function into implode.

In that case you're returning an array from the function and passing that into implode - that checks out.

edit/adding: that anonymous function would be instanceof Closure.

Closure !== array
Comments