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"
}
<?php
foreach($d as $k => $v)
{
$d2 = explode(':',$v);
$array[$d2[0]] = $d2[1];
}
?>
This should work:
$arr = array();
$d = explode(',', $string);
for($d as $item){
list($key,$value) = explode(':', $item);
$arr[$key] = $value;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With