Reputation: 9221
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?
Upvotes: 0
Views: 221
Reputation: 47873
Iterate over you single quote wrapped csv strings and return the first value from each string after parsing.
Code: (Demo)
$aa = [
"'a1','a2'",
"'b1','b2'",
"'c1','c2'"
];
var_export(
array_map(
fn($csv) => str_getcsv($csv, ',', "'")[0],
$aa
)
);
If you require a lone delimited string, just call implode()
on the result array above.
Upvotes: 0
Reputation: 2254
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;
}
Upvotes: 3