1

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

2
  • This is trivially easy to do with a simple foreach($arr as $key => $value). Are you having trouble with something in particular? Commented May 28, 2014 at 18:41
  • Sounds easy enough. Can you show the code where you have tried to implement this and explain what is not working? Commented May 28, 2014 at 18:41

3 Answers 3

1

Given your array, $array:

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

echo $str; // 3:15;30:1;1:1;
Sign up to request clarification or add additional context in comments.

1 Comment

thanks to all, this is the solution that I use, this doesn't work for me before because the mysql server where i get the array was down, Sorry, I have to stressed by a lot of hours with the php code editor.
1

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) ) 
);

2 Comments

This is easily the best solution, but I think a couple line breaks would make it a lot easier to read.
Now that I look closer, OP apparently wants ; after every key-value pair, including the last. You could fix your code to match by removing the first argument to implode and changing the callback to return "$k:$v;".
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.