1

I Have $str string variable & i want to make a $array array from $str string.

    $str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|sem";

    Final array should be 
    $array = array(
    'BKL'=> 'bkl',
    'EXH' => 'exh',
    'FFV' => 'ffv',
    'AUE' => 'aue'  
    );
Charles
  • 50,943
  • 13
  • 104
  • 142
atpatil11
  • 438
  • 4
  • 13

5 Answers5

6

This should do the trick

$str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|sem";

$final = array();

foreach (explode(',', $str) as $pair) {
  list($key, $value) = explode('|', $pair);
  $final[$key] = $value;
}

print_r($final);

Output

Array
(
    [BKL] => bkl
    [EXH] => exh
    [FFV] => ffv
    [LEC] => lec
    [AUE] => aue
    [SEM] => sem
)
maček
  • 76,434
  • 37
  • 167
  • 198
1

Try this,

<?php
  $str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|sem";

  $split = explode(',', $str);
  $arr = array();
  foreach($split as $v){
    $tmp = explode('|', $v);
    $arr[$tmp[0]] = $tmp[1];
  }

  print_r($arr);
?>

Output:

Array
(
    [BKL] => bkl
    [EXH] => exh
    [FFV] => ffv
    [LEC] => lec
    [AUE] => aue
    [SEM] => sem
)
Muthu Kumaran
  • 17,682
  • 5
  • 47
  • 70
1
$str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|sem";

$result = array();
$node = explode(',', $str);

foreach ($node as $item) {
    $temp = explode('|', $item);
    $result[$temp[0]] = $temp[1];
}
vidura
  • 65
  • 1
  • 1
  • 7
0
$str = "BKL|bkl,EXH|exh,FFV|ffv,LEC|lec,AUE|aue,SEM|sem";
$out = array;
$arr = explode(',', $str);

foreach ($arr as $item) {
    $temp = explode('|', $item);
    $out[$temp[0]] = $temp[1];
}
AlecTMH
  • 2,615
  • 23
  • 26
0

You should have a look at explode in the php manual.

EirikO
  • 617
  • 8
  • 19
  • please avoid ["read the manual"-type answers](http://meta.stackexchange.com/questions/98959/rtfm-like-answers-flag-them-or-allow-them) – maček Jan 08 '13 at 06:55
  • No problem, EirikO. I reviewed and updated some of your other answers. I hope this sets you off on the right track. – maček Jan 08 '13 at 07:43