How to create a particular array from the string in php

advertisements

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


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
)