Puneet
Puneet

Reputation: 440

how to get associative array from string

I have one string like:-

$attributes = "id=1 username=puneet mobile=0987778987 u_id=232";

Now, I want to get it in following associative array format:-

$attributes{'id' => 1, 'username' => puneet, 'mobile' => 0987778987, 'u_id' => 232}

Note:- These all values are separated by space only. Any help will be appreciable.

Thanks in advance

Upvotes: 3

Views: 111

Answers (5)

Shashika Silva
Shashika Silva

Reputation: 55

I think you have to split this string two times

  1. divide with space
  2. divide with '='

Upvotes: -1

Deep123
Deep123

Reputation: 391

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 put of this code is

Array ( [id] => 1 [username] => puneet [mobile] => 0987778987 [u_id] => 232 )

Upvotes: 0

Teneff
Teneff

Reputation: 32158

I can suggest you to do it with a regular expression:

$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

Upvotes: 2

David Kiger
David Kiger

Reputation: 1996

$final_array = array();

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

Upvotes: 3

user1646111
user1646111

Reputation:

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

EXPLODE

Upvotes: 2

Related Questions