0

I have the following string

sender=48&destination=51&message=hi+good&sender=48&destination=49&message=good+boy

Please help me convert that into PHP array as following

 array = array(
     'sender'=>48,
     'destination'=>51,
     'message'=>hi+good,
     'sender'=>48,
     'destination'=>49,
     'message'=>good+boy
 );

Note: Its not PHP GET.

tapaljor
  • 237
  • 1
  • 6
  • 21
  • Its not a PHP GET. @FastSnail I failed with link you provided. – tapaljor Nov 24 '16 at 05:26
  • one thing I have noticed here same array key not able to come in single array. e.g : sender,message,destination 2 times – RJParikh Nov 24 '16 at 05:38
  • your desire output will wrong. your array should be like `Array ( [0] => Array ( [sender] => 48 ) [1] => Array ( [destination] => 51 ) [2] => Array ( [message] => hi+good ) [3] => Array ( [sender] => 48 ) [4] => Array ( [destination] => 49 ) [5] => Array ( [message] => good+boy ) )` – RJParikh Nov 24 '16 at 05:43
  • and have you **tried anything** so far yourself? – Franz Gleichmann Nov 24 '16 at 05:49
  • I tried. I was close but following answer completed it. – tapaljor Nov 24 '16 at 05:53

2 Answers2

3

This should work as inteded, to solve this problem, you just need to use explode() correctly, otherwise it's easy.

Here you go :

$firstarr=explode('&',$yourstring);
$desiredarr=array();
foreach($firstarr as $pair)
{
    $exp_pair=explode('=',$pair);
    $desiredarr[$exp_pair[0]]=$exp_pair[1];
}

print_r($desiredarr);
Nikunj Sardhara
  • 638
  • 1
  • 5
  • 20
1

If it is from query string then you can just use $_REQUEST otherwise you need to explode() string using & as separator. Then for each item in array that explode() generate, you split with = and add it to final array
or using parse_str().

Zamrony P. Juhara
  • 5,222
  • 2
  • 24
  • 40