vietean
vietean

Reputation: 3033

Combine an array to string in PHP

I have a below array in PHP

$arrOrders['remains'] = 'ASC';
$arrOrders['rate']    = 'DESC';

How can I use combine to a string like just with native function?

$str = 'remain ASC, rate DESC';

Upvotes: 1

Views: 849

Answers (4)

Blem
Blem

Reputation: 822

you are looking for implode, but it dose not include the keys, but the first comment on the page is a function for including keys

/**
 * Implode an array with the key and value pair giving
 * a glue, a separator between pairs and the array
 * to implode.
 * @param string $glue The glue between key and value
 * @param string $separator Separator between pairs
 * @param array $array The array to implode
 * @return string The imploded array
 */
function array_implode( $glue, $separator, $array ) {
    if ( ! is_array( $array ) ) return $array;
    $string = array();
    foreach ( $array as $key => $val ) {
        if ( is_array( $val ) )
            $val = implode( ',', $val );
        $string[] = "{$key}{$glue}{$val}";

    }
    return implode( $separator, $string );

}


$arrOrders = array(
    'remains' => 'ASC',
    'rate'      => 'DSC'
);
$str = array_implode( ' ', ', ', $arrOrders);

Upvotes: 1

Aurelio De Rosa
Aurelio De Rosa

Reputation: 22162

You can do this:

$string = '';
foreach($arrOrders as $key => $value)
   $string = $string . "$key $value, ";
$string  = rtrim($string, ', '); // cut the last comma at the end of the string

echo $string // remains ASC, rate DESC

Upvotes: 2

Godzilla
Godzilla

Reputation: 318

use a foreach and implode()

foreach ($arrOrders as $key => $val) {
$temp[] = "$key $val";
}
$order = implode(',', $temp);

Upvotes: 3

Stefan Gehrig
Stefan Gehrig

Reputation: 83622

$a = array(
    'remains' => 'ASC',
    'rate'      => 'DSC'
);  

echo implode(', ', array_map(function($v1, $v2) {
    return sprintf('%s %s', $v1, $v2);
}, array_keys($a), array_values($a)));
// remains ASC, rate DSC

Upvotes: 5

Related Questions