Gmo
Gmo

Reputation: 151

php function implode tweaking

im trying to print an array using implode, but i want to tweak it, so the "glue" of the implode show every two element, and not in every element.

$nombreNombre=array('josh','13','mike','44','dude','98','scott','450');
echo '<li>' . implode('</li><li>', $nombreNombre).'</li>

with that im getting:

  • josh
  • 13
  • mike
  • 44
  • dude
  • 98
  • scott
  • 450
  • and i want:

  • josh 13
  • mike 44
  • dude 98
  • scott 450
  • Upvotes: 4

    Views: 304

    Answers (1)

    Daniel Lubarov
    Daniel Lubarov

    Reputation: 7924

    You could run $nombreNombre through array_chunk, do an array_map to convert each pair to a string, then implode.

    $arr = array('josh','13','mike','44','dude','98','scott','450');
    $arr = array_chunk($arr, 2);
    function repr($pair) { list($a, $b) = $pair; return "$a $b"; }
    $arr = array_map("repr", $arr);
    echo '<li>' . implode('</li><li>', $arr) . '</li>';
    

    Upvotes: 6

    Related Questions