Sau Thien Thu Sau Thien Thu - 6 months ago 52
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

I want to return:

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download