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?

Echilon
  • 10,064
  • 33
  • 131
  • 217
medk
  • 9,233
  • 18
  • 57
  • 79
  • 5
    Your `$arr` is not multidimensional. – nkr Nov 11 '12 at 13:26
  • 1
    Read about explode function in php – Oras Nov 11 '12 at 13:27
  • 1
    @Oras the explode function (http://php.net/manual/en/function.explode.php) can only split by one delimiter. This would not yield an associative array like the OP wants. – Joshua Dwire Nov 11 '12 at 13:30
  • 1
    @jdwire He can use it twice inside a loop generated based on the first use of explode. – Oras Nov 11 '12 at 13:32
  • 1
    @Oras Right, he can use it like GBD is suggesting. – Joshua Dwire Nov 11 '12 at 13:35
  • ok now for both GBD and air4x answers they are functional, but for an intense traffic app, which is better and less resource consuming? – medk Nov 11 '12 at 13:38
  • 1
    @medk just test it online or do some intensief loops while registering the time consumed to execute the script http://stackoverflow.com/questions/11235369/measuring-the-elapsed-time-between-code-segments-in-php/11235396 – HamZa Nov 11 '12 at 13:43

2 Answers2

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);
GBD
  • 15,847
  • 2
  • 46
  • 50
3

Try

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