php - Join array with a comma every two elements -


i have 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 want join above array , every 2 words. expected result below

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

how can that?

please try this, uses array_chuck, explode, , 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 forloop if don't nested methods.

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

output: red blue, yellow dog, cat fish, mountain


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -