how to separate array with commas?

2019-08-08 18:51发布

i have this $_categories as array()

<?php print_r($_categories); ?> is this: Array ( [0] => 13 [1] => 7 )

what i need is to extract de values 13 and 7 into this format: 13,7 (without comma after the last value).

i have this code but is not there yet... the result is: 137 and not 13,7

<?php
    if ( is_array($_categories) ) {
        foreach ($_categories as $key => $value) {
            $out = array();
            array_push($out, $value);
            echo implode(', ', $out);
        }
    }
    else {
        echo '<li>There are no saved values yet.</li>';
    }
?> 

Thanks, nelson

2条回答
在下西门庆
2楼-- · 2019-08-08 19:24

Directly use

echo implode(', ', $_categories);
查看更多
何必那么认真
3楼-- · 2019-08-08 19:43

Everytime you are implodeing just one element,and echoing just it. Try like this:

$out = array();   //putting outside of the loop
foreach ($_categories as $key => $value) {
    array_push($out, $value);
}    
echo implode(', ', $out);   //putting outside of the loop
查看更多
登录 后发表回答