3

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

5 Answers 5

3
$final_array = array(); $kvps = explode(' ', $attributes); foreach( $kvps as $kvp ) { list($k, $v) = explode('=', $kvp); $final_array[$k] = $v; } 
Sign up to request clarification or add additional context in comments.

2 Comments

is there any function available to acheive this task?? I am looking for function rather than loop
@Puneet Write a function that take $attributes as a parameter and returns $final_array
2

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

Comments

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

EXPLODE

Comments

0

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 ) 

Comments

-1

I think you have to split this string two times

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.