简体   繁体   中英

How to transform array to comma separated words string without using implode()

My array looks like this:

Array
(
    [0] => lorem
    [1] => ipsum
    [2] => dolor
    [3] => sit
    [4] => amet
)

How to transform this to a string like this with php?

$string = 'lorem, ipsum, dolor, sit, amet';

使用 join() - 你可以使用 join,它是 implode 的别名,也更具可读性:

echo join(',',$array);
$str="";
foreach($yourarray as $key=>$value){
 $str.=$value.",";
}
rtrim($str, ",");
echo $str;
<?php

$array = array("1" => "lorem",  
              "2" => "ipsum",
              "3"  => "dolor", 
              "4" => "sit",
              "5" => "amet"
              );



$string = "";       

foreach( $array as $key => $value ){
     $string.=$value.",";
}

echo $string;

use below solution:

<?php
$array = Array
        (
            0 => 'lorem',
            1 => 'ipsum',
            2 => 'dolor',
            3 => 'sit',
            4 => 'amet',
        );

$str = '';

foreach($array as $a){
$str .= $a.', ';
}

echo rtrim($str, ',');

output

lorem, ipsum, dolor, sit, amet

using for loop:

$array = [
    0 => 'lorem',
    1 => 'ipsum',
    2 => 'dolor',
    3 => 'sit',
    4 => 'amet',
];

$counter = count($array)-1;
$string = '';

 for ($i=0; $i<=$counter; $i++) {
      $string .= $array[$i].', ';
 }

 echo rtrim($string, ",");

Use implode function to convert,a string into array. Please try this,it will give you the output you want

<?php
    $array = Array
        (
            0 => 'lorem',
            1 => 'ipsum',
            2 => 'dolor',
            3 => 'sit',
            4 => 'amet',
        );
    $string = implode(",",$array);
    echo '$string = '."'".$string."'";
?>

使用 for 循环并将项目连接到字符串。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM