0

I have a string like this:

$str = '35-3|24-6|72-1|16-5';

I want to generate an array:

$arr = array (

    35 => 3,
    24 => 6,
    72 => 1,
    16 => 5

);

What's the best and simplest way?

7
  • 5
    Your $arr is not multidimensional. Commented Nov 11, 2012 at 13:26
  • 1
    Read about explode function in php Commented Nov 11, 2012 at 13:27
  • 1
    @Oras the explode function (php.net/manual/en/function.explode.php) can only split by one delimiter. This would not yield an associative array like the OP wants. Commented Nov 11, 2012 at 13:30
  • 1
    @jdwire He can use it twice inside a loop generated based on the first use of explode. Commented Nov 11, 2012 at 13:32
  • 1
    @Oras Right, he can use it like GBD is suggesting. Commented Nov 11, 2012 at 13:35

2 Answers 2

10

You can try as below

$str = '35-3|24-6|72-1|16-5';

$data = explode("|",$str);
$arr = array();
foreach($data as $value){
  $part = explode('-',$value);
  $arr[$part[0]]=$part[1];
}

var_dump($arr);
Sign up to request clarification or add additional context in comments.

1 Comment

hi, can you explian in depth?
3

Try

if (preg_match_all('/(\d+)\-(\d*)/', $str, $matches)) {
  $arr = array_combine($matches[1], $matches[2]);
}

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.