manespgav
manespgav

Reputation: 177

PHP, array to string with separator characters

I have an array like this:

Array (
       [3] => 15 
       [30] => 1 
       [1] => 1 )

I want to convert it into a string like this: $string = "3:15;30:1;1:1;"

Thanks you in advance

Upvotes: 1

Views: 502

Answers (3)

Danijel
Danijel

Reputation: 12689

Here is one-liner:

$array = array(
    3 => 15,
    30 => 1,
    1 => 1,
);

// "3:15;30:1;1:1" ( without last semicolon )
$string = implode( ';', array_map( 
    function($v, $k) { 
        return "$k:$v"; 
    }, $array, array_keys($array) ) 
);

// "3:15;30:1;1:1;" ( with last semicolon  )
$string = implode( array_map( 
    function($v, $k) { 
        return "$k:$v;"; 
    }, $array, array_keys($array) ) 
);

Upvotes: 1

Mark Miller
Mark Miller

Reputation: 7447

Given your array, $array:

$str = '';
foreach ($array as $k => $v) {
    $str .= $k . ':' . $v . ';';
}

echo $str; // 3:15;30:1;1:1;

Upvotes: 1

Kodlee Yin
Kodlee Yin

Reputation: 1089

Here's a quick and easy way to do this.

function delimit(&$anArray) {
    $preArray = array();
    foreach($anArray as $key => $value)
        $preArray[] "$key:$value"
    return implode(";", $preArray);
}

Edit: This is the way to go if you want to "fence post" the array, meaning you don't want to append an extra semi-colon at the end of the string.

Upvotes: 0

Related Questions