Search code examples
phparraysimplode

Join array with a comma every two elements


I have an array

$str = $query->get_title(); //Red blue yellow dog cat fish mountain
$arr = explode(" ",$str);

//output of $arr
Array
(
    [0] => Red 
    [1] => blue 
    [2] => yellow 
    [3] => dog 
    [4] => cat 
    [5] => fish 
    [6] => mountain
)

Now I want to join the above array with , every two words. The expected result is as below

$result = "Red blue, yellow dog, cat fish, mountain";

How can I do that?


Solution

  • Please try this, it uses array_chuck, explode, and implode.

    <?php
    
    $str = "Red blue yellow dog cat fish mountain";
    
    $result = implode(', ', array_map(function($arr) {
        return implode(' ', $arr);
    }, array_chunk(explode(' ', $str), 2)));
    
    echo $result;
    

    Output: Red blue, yellow dog, cat fish, mountain


    Another method using a forloop if you don't like nested methods.

    <?php
    
    $str = "Red blue yellow dog cat fish mountain";
    
    $words = explode(' ', $str);
    
    foreach ($words as $index => &$word)
        if ($index % 2)
            $word .= ',';
    
    $result = implode(' ', $words);
    
    echo $result;
    

    Output: Red blue, yellow dog, cat fish, mountain