Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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'  
    );
share|improve this question

5 Answers 5

up vote 6 down vote accepted

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
)
share|improve this answer
    
Tons of thanks to Mr. maček. Keep sharing. –  atpatil11 Jan 8 '13 at 6:55

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
)
share|improve this answer
$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];
}
share|improve this answer
$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];
}
share|improve this answer

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

share|improve this answer
    
please avoid "read the manual"-type answers –  maček Jan 8 '13 at 6:55
    
Ok, thank you for telling me :) –  EirikO Jan 8 '13 at 7:08
    
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 8 '13 at 7:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.