The string I am trying to split is $item['category_names']
which for example contains Hair, Fashion, News
I currently have the following code:
$cats = explode(", ", $item['category_names']);
foreach($cats as $cat) {
$categories = "<category>" . $cat . "</category>\n";
}
I want the outcome of $categories
to be like the following so I can echo it out later somewhere.
<category>Hair</category>\n
<category>Fashion</category>\n
<category>News</category>\n
Not sure if I am going the right way about this?
In your code you are overwritting the $categories variable in each iteration. The correct code would look like:
update: as @Nanne suggested, explode only on ','
The error in your code is this:
You are overwriting
$categories
at each iteration, it should be:Not sure if I am going the right way about this?
find and replace isn't what explode is for. If you just want to correct the code error - see above.
This is more efficient:
And this also accounts for variable whitespace:
Without a for loop
if you use this:
the $categories string is overwritten each time, so "hair" and "fasion" are lost..
if you however add a dot before the equal sign in the for loop, like so:
the $catergories string will consist of all three values :)
PHP explode array by loop demo: http://sandbox.onlinephpfunctions.com/code/086402c33678fe20c4fbae6f2f5c18e77cb3fbc2
its works for me