3

Is there any way to add an increment value while imploding an array?

This is the piece of code I'd like to have the increment value:

$entries = '<ul class="repeatData"><li class="listEntry1">' . implode('</li><li class="listEntry'. $countme .'">', $data) . '</li></ul>';

I'd like somehow to make the variable $countme increment every time it implodes each array value, if this is even possible.

otinanai
  • 3,987
  • 3
  • 25
  • 43

5 Answers5

8

You cannot do this with implode, but look into applying an anonymous function to the array. You can probably do what you want with not much more code.

$entries = '<ul class="repeatData">';
$countme = 1;

array_walk($data, function ($element) use (&$entries, &$countme) { 
    $entries .= '<li class="listEntry'. $countme .'">'. $element . '</li>';
    $countme++;
});
$entries .= "</ul>";

Explanation: I have written an anonymous function, told it about $entries and $counter (so it is a closure, in fact) so that it can modify them from inside its scope, and passed it to array_walk, which will apply it to all elements of the array.

Tom Macdonald
  • 6,433
  • 7
  • 39
  • 59
  • I would really appreciate an example here. Your suggestion sound fast and promising. – otinanai Oct 21 '13 at 16:46
  • A simple `for` loop would do the same here, but faster.. But however, more important is that it will not solve the problem. It is requested to implode `$data` but in your case it will just append the `
  • ..` to every(!) element of `$data`
  • – hek2mgl Oct 21 '13 at 16:53
  • Yup, I just fixed that bug. Trying to get my answer in too fast, mea culpa! – Tom Macdonald Oct 21 '13 at 16:56
  • 2
    And yes a for loop is a faster answer, but closures are more fun, and a good technique for less tractable problems than html lists. I'm future-proofing the OP! – Tom Macdonald Oct 21 '13 at 16:57
  • 2
    He wants to join the elements of the array into an html list. That is what I have done. I do not understand what the issue is. I know what implode() does. – Tom Macdonald Oct 21 '13 at 17:13
  • 2
    sorry you are right, the code is ok and will do the job. I looked too much at the return value of `array_map` and not at the `&entries` param of the closure. – hek2mgl Oct 21 '13 at 17:14
  • 2
    I see! array_walk would have been more correct than array_map. – Tom Macdonald Oct 21 '13 at 17:17
  • @ravloony yes, I think that array_walk() would being better here. – hek2mgl Oct 21 '13 at 17:18
  • There you are, I have fixed it. – Tom Macdonald Oct 21 '13 at 17:20
  • have already upvoted your answer after I got the `&$entries` usage. After all I would say using `array_walk` with a closure looks like the cleanest solution. ;) – hek2mgl Oct 21 '13 at 17:23
  • Glad you switched to the `array_walk()` from the map. – Orbling Oct 21 '13 at 17:31
  • 1
    Just perfect! It does exactly what I was after. – otinanai Oct 21 '13 at 18:19