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


I can suggest you do it with a regex:

$str = "id=1 username=puneet mobile=0987778987 u_id=232";
$matches = array();
preg_match_all( '/(?P<key>\w+)\=(?P<val>[^\s]+)/', $str, $matches );
$res = array_combine( $matches['key'], $matches['val'] );

      



working example in phpfiddle

+2


source


$final_array = array();

$kvps = explode(' ', $attributes);
foreach( $kvps as $kvp ) {
    list($k, $v) = explode('=', $kvp);
    $final_array[$k] = $v;
}

      



+3


source


$temp1 = explode(" ", $attributes);
foreach($temp1 as $v){
 $temp2 = explode("=", $v);
 $attributes[$temp2[0]] = $temp2[1];
}

      

EXPLODE

+2


source


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


I think you need to split this line two times

  • share with space
  • divide '='

-1


source







All Articles