2

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"
}

3 Answers 3

6
<?php 
foreach($d as $k => $v)
{
    $d2 = explode(':',$v);
    $array[$d2[0]] = $d2[1];
}
?>
Sign up to request clarification or add additional context in comments.

2 Comments

$array must be initialized first $array = array(); before foreach
@Gtx PHP handles this without error though I agree that it should be initialised
6

This should work:

$arr = array();
$d = explode(',', $string);
for($d as $item){
   list($key,$value) = explode(':', $item);
   $arr[$key] = $value;
}

2 Comments

got this error Parse error: syntax error, unexpected T_VARIABLE, expecting ';' in C:\xampp\htdocs\Colosus\modul\barang\explode.php on line 19
@Wawan Guessing I'd need to look at your actual code, guessing there's a missing ; somewhere, or a stray brace.
1

This is a simple solution using loops:

$string = "a:1,b:2,c:3,d:4,e:5,f:6,g:7";
$pairs = explode(',', $string);
$a = array();
foreach ($pairs as $pair) {
    list($k,$v) = explode(':', $pair);
    $a[$k] = $v;
}
var_export($a);

You can also do this (in PHP >= 5.3) in a more functional manner:

$string = "a:1,b:2,c:3,d:4,e:5,f:6,g:7";
$pairs = explode(',', $string);
$items = array_map(
    function($e){
        return explode(':', $e);
    },
    $pairs
);
$a = array_reduce(
    $items,
    function(&$r, $e) {
        $r[$e[0]] = $e[1];
        return $r;
    },
    array()
);

var_export($a);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.