Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exploding an array and removing prefix

I an trying to create an array using explode for a string.

Here is my string:

$string = "a:1,b:2,c:3,d:4,e:5,f:6,g:7";

And here's my complete code:

$string = "a:1,b:2,c:3,d:4,e:5,f:6,g:7";
$d = explode(',', $string);
echo '<pre>';
var_dump($d);

and after that i got the result like this..

array(7) {
  [0]=>
  string(3) "a:1"
  [1]=>
  string(3) "b:2"
  [2]=>
  string(3) "c:3"
  [3]=>
  string(3) "d:4"
  [4]=>
  string(3) "e:5"
  [5]=>
  string(3) "f:6"
  [6]=>
  string(3) "g:7"
}

How can I create an array like this instead?:

array(7) {
  ["a"]=>
  string(1) "1"
  ["b"]=>
  string(1) "2"
  ["c"]=>
  string(1) "3"
  ["d"]=>
  string(1) "4"
  ["e"]=>
  string(1) "5"
  ["f"]=>
  string(1) "6"
  ["g"]=>
  string(1) "7"
}
like image 732
Wawan Brutalx Avatar asked Sep 18 '26 18:09

Wawan Brutalx


2 Answers

<?php 
foreach($d as $k => $v)
{
    $d2 = explode(':',$v);
    $array[$d2[0]] = $d2[1];
}
?>
like image 52
DigitalDaigor Avatar answered Sep 21 '26 07:09

DigitalDaigor


This should work:

$arr = array();
$d = explode(',', $string);
for($d as $item){
   list($key,$value) = explode(':', $item);
   $arr[$key] = $value;
}
like image 45
Mark Elliot Avatar answered Sep 21 '26 07:09

Mark Elliot