medk
medk

Reputation: 9529

Generate an array from a string

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?

Upvotes: 0

Views: 114

Answers (2)

air4x
air4x

Reputation: 5683

Try

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

Upvotes: 3

GBD
GBD

Reputation: 15981

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);

Upvotes: 10

Related Questions