Skip to content
Advertisement

Explode a string to array with key => value

I have string is:

$string = '200AUD, 150USD, 80GBP, 1250000VND';

How Can I convert from $string to an array with key => value.

Key: AUD => Value 200
Key: USD => Value 150
Key: GBP => 80
Key: VND => 1250000

Updated:

@Mark Baker my php version is 5.4 so I cannot test your code, thanks

@Aleatoric I’m use this code, but the array return some space character on key and value:

                Array
(
    [ CHF] => 130 
    [  GBP] =>  80 
    [  USD] =>  125 
    [  DKK] =>  750 
    [  PLN] =>  400 
    [  CZK] =>  2500 
    [  YTL] =>  175 
    [  BGN] =>  175 
    [  RUB] =>  4000 
    [  RON] =>  400 
    [  SEK] =>  1000 
)

I have use trim() to strips all space, but can you tell me best idea for this issue without use trim() function?

Advertisement

Answer

You’re going to have to explode the string first with:

$array1 = explode(',', $string);

and then iterate over the elements with a foreach loop to split the strings and put them into an associative array:

$array2 = array();
foreach($array1 as $string){
    $currency = trim(preg_replace("/[0-9]+/", "", $string));
    $value = trim(preg_replace("/[a-zA-Z]+/", "", $string));
    $array2[$currency] = $value;
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement