Sau Thien Thu Sau Thien Thu - 1 month ago 13
PHP Question

Convert String to Array in php?

I want to convert from String to Array in PHP, but not cant, do you help me, please ?

$str = "A,B
battery_counter,step1
battery_explanation,step2
calc_coupon,step3
broadband_standard,step4";


I want to return:

return array(
'A' => 'B',
'battery_counter' => 'step1',
'battery_explanation' => 'step2',
'calc_coupon' => 'step3',
'broadband_standard' => 'step4'
)

JBH JBH
Answer Source

Without knowing more about the limits of your software:

$return_array = array();
$exploded_var = explode("\n",$str);
foreach($exploded_var as $pair_var){
    $tmp = explode(",",$pair_var);
    $return_array[$tmp[0]] = $tmp[1];
}
return $return_array;

You need to explode the string twice, once to get to the "pair strings" (e.g., "a,b") and the second time to split the pair strings apart.

WARNING: My solution is 100% specific to how you presented the $str variable. It is not expandable to any arbitrary string.