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.

5
  • Its not a PHP GET. @FastSnail I failed with link you provided. Commented Nov 24, 2016 at 5:26
  • one thing I have noticed here same array key not able to come in single array. e.g : sender,message,destination 2 times Commented Nov 24, 2016 at 5: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 ) ) Commented Nov 24, 2016 at 5:43
  • and have you tried anything so far yourself? Commented Nov 24, 2016 at 5:49
  • I tried. I was close but following answer completed it. Commented Nov 24, 2016 at 5:53

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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().

3 Comments

If I explode it comes Array([0]=sender=48 ..
How do you call explode()?
$array = explode("&", $array); The key is coming in 0, 1 series.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.