Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP explode array then loop through values and output to variable

Tags:

arrays

php

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?

like image 879
Marc Sanders Avatar asked May 18 '12 10:05

Marc Sanders


3 Answers

In your code you are overwritting the $categories variable in each iteration. The correct code would look like:

$categories = '';
$cats = explode(",", $item['category_names']);
foreach($cats as $cat) {
    $cat = trim($cat);
    $categories .= "<category>" . $cat . "</category>\n";
}

update: as @Nanne suggested, explode only on ','

like image 75
Maxim Krizhanovsky Avatar answered Oct 23 '22 02:10

Maxim Krizhanovsky


Without a for loop

$item['category_names'] = "Hair,   Fashion,   News";
$categories = "<category>".
        implode("</category>\n<category>", 
        array_map('trim', explode(",", $item['category_names']))) . 
        "</category>\n";
echo $categories;
like image 2
Aaron W. Avatar answered Oct 23 '22 04:10

Aaron W.


if you use this:

$cats = explode(", ", $item['category_names']);
foreach($cats as $cat) {
$categories = "<category>" . $cat . "</category>\n";
}

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:

$cats = explode(", ", $item['category_names']);
foreach($cats as $cat) {
$categories .= "<category>" . $cat . "</category>\n";
}

the $catergories string will consist of all three values :)

like image 1
Wampie Driessen Avatar answered Oct 23 '22 02:10

Wampie Driessen