How to create a comma-separated list from an array in PHP?

WebTechRiser.com > PHP > How to create a comma-separated list from an array in PHP?

Any programming language may occasionally need to convert all the elements of an array into a comma-separated list. In PHP language, this can be done easily using its built-in function, implode().

The signature of the implode() function from the official documentation of PHP is as follows:

Syntax:

implode (string $ separator, array $ array): string

This function will convert the elements of an array into a string element while maintaining their original order.

Each element in the integrated string will have one separator mentioned in the method’s signature.

How to Convert String Array

Array
(
    [0] => apple
    [1] => windows
    [2] => linux
)

Output:

apple, windows, linux

How to Convert Numeric Array

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
    [6] => 6
    [7] => 7
)

Output

0, 1, 2, 3, 4, 5, 6, 7

How to Convert Key-Value Pair Array

If you want to implode an array as key-value pairs, this method comes in handy. The third parameter is the symbol used between the key and value.

<?php
function mapped_implode($glue, $array, $symbol = '=') {
    return implode($glue, array_map(
            function($k, $v) use($symbol) {
                return $k . $symbol . $v;
            },
            array_keys($array),
            array_values($array)
            )
        );
}

$arr = [
    'x'=> 5,
    'y'=> 7,
    'z'=> 99,
    'hello' => 'World',
    7 => 'Foo',
];

echo mapped_implode(', ', $arr, ' is ');
?>

Output

x is 5, y is 7, z is 99, hello is World, 7 is Foo

The technique of creating comma-separated lists from arrays is simple. Many times it may be necessary to create arrays from strings in reverse. In that case, the official site of PHP mentions to use the explode(), preg_split(), or http_build_query() functions.

Category PHP

Leave Your Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.