How to get an associative array from a string
I have one line like: -
$attributes = "id=1 username=puneet mobile=0987778987 u_id=232";
Now I want to get it in the following associative array format: -
$attributes{'id' => 1, 'username' => puneet, 'mobile' => 0987778987, 'u_id' => 232}
Note. - All these values are separated only by a space. Any help would be appreciated.
Thank you in advance
+3
source to share
5 answers
this code will solve your problem.
<?php
$attributes = "id=1 username=puneet mobile=0987778987 u_id=232";
$a = explode ( ' ', $attributes) ;
$new_array = array();
foreach($a as $value)
{
//echo $value;
$pos = strrpos($value, "=");
$key = substr($value, 0, $pos);
$value = substr($value, $pos+1);
$new_array[$key] = $value;
}
print_r($new_array);
?>
out from this code
Array ( [id] => 1 [username] => puneet [mobile] => 0987778987 [u_id] => 232 )
0
source to share