-4

I have something like this :

$string = "a:3;b:4;c:1;d:9";

and I want:

$array = ['a'=>3, 'b'=> 4, 'c'=>1, 'd'=>9];

Thanks

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • 4
    Very cool. Can you let us know when you get it? – Jay Blanchard Jul 21 '15 at 17:52
  • Stick to array functions and foreach. learn more php basics bro. – Mahdyfo Jul 21 '15 at 17:55
  • 2
    This almost looks like a serialized string.. just a warning, if you're dealing with serialized strings, stop. Use the proper serialization functions. – Rob W Jul 21 '15 at 18:00
  • Related/simpler approaches: [PHP Split Delimited String into Key/Value Pairs (Associative Array)](http://stackoverflow.com/q/5290342) – mario Jul 21 '15 at 18:05

1 Answers1

1
$string = "a:3;b:4;c:1;d:9";

$exploded = explode(";",$string);

$newArr = array();
foreach ($exploded as $single){
   $inner =  explode(":",$single);
   $newArr[$inner[0]] =   $inner[1];
}

In the end use $newArr;

Pratik Joshi
  • 11,485
  • 7
  • 41
  • 73
  • 2
    http://meta.stackoverflow.com/questions/258206/what-is-a-help-vampire – Mahdyfo Jul 21 '15 at 17:54
  • 2
    I didn't downvoted you buddy. It works but helping with the basics is not productive. – Mahdyfo Jul 21 '15 at 17:56
  • Try here http://phpfiddle.org/ – Pratik Joshi Jul 21 '15 at 17:57
  • Stating *that* it works isn't as helpful as explaining / documenting *how*. For all we know OP could already have stumbled across some whacky `explode`/`foreach` code before, but didn't figure out how it behaved. – mario Jul 21 '15 at 18:04