Home » Php » PHP explode array then loop through values and output to variable

PHP explode array then loop through values and output to variable

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&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 ‘,’

Answer:

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;

Answer:

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 🙂

Answer:

PHP explode array by loop
demo: http://sandbox.onlinephpfunctions.com/code/086402c33678fe20c4fbae6f2f5c18e77cb3fbc2

its works for me

<?php

$str = "name:john,hone:12345,ebsite:www.23.com";

$array=explode(",",$str);

if(count($array)!=0)
{
foreach($array as $value)
{

    $data=explode(":",$value);

      echo $data[0]."=".$data[1];


    echo ' ';

}
}
?>

Answer:

The error in your code is this:

$categories = "<category>" . $cat . "</category>\n";

You are overwriting $categories at each iteration, it should be:

$categories .= "<category>" . $cat . "</category>\n";

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:

$categories = "<category>" .
    str_replace(', ', "</category>\n<category>", $input) . 
    "</category>\n";

And this also accounts for variable whitespace:

$categories = "<category>" . 
    preg_replace('@\s*,\s*@', "</category>\n<category>", $input) . 
    "</category>\n";