phploopsforeach

Loop over an array of csv strings containing quoted values then return the first value from each csv string


I am trying loop over an array with a foreach().

When I tested the code below,

$aa = array("'a1','a2'","'b1','b2'","'c1','c2'");
foreach($aa as $bb){
    $cc = array($bb);//var_dump($cc);  (1) { [0]=> string(9) "'a1','a2'" }...
    foreach($cc as $dd){
        echo $dd.'<br />';
        break;
    }
}

It will output:

'a1','a2'
'b1','b2'
'c1','c2'

But I want a1,b1,c1.

Wrong with $cc = array($bb)...

What is the problem?


Solution

  • You have one level array, not two. Elements are just strings for php, not arrays. That's why your code doesn't work.

    Replace your $cc = array($bb) string with smth like this:

    $cc = explode(',', $bb);
    foreach($cc as $dd){
        echo trim($dd, "'").'<br />';
        break;
    }