2

Im using PHP to output the category information from an RSS feed:

foreach(item_category()) as $category) { 
    $source = $category->cat_name; 
    echo $source.'.png';
}

Where item_category is an array of category names. I then have a set of corresponding images I've like to display against each item.

At the moment my output looks like this:

category1.pngcategory2.pngcategory3.png

but I need:

category1category2category3.png

How can I construct the correct file name with the single occurence of the file extension at the end of the string?

6 Answers 6

5
foreach(item_category() as $category) { 
    $source = $category->cat_name; 
    echo $source;
}
echo'.png'
Sign up to request clarification or add additional context in comments.

Comments

1

Here's an alternative solution that doesn't use a local variable

echo implode('', array_map(function($c){
    return $c->cat_name;
}, item_category()) . '.png';

(Requires PHP >= 5.3)

Comments

0
foreach(item_category() as $category)
    $source .= $category->cat_name;
echo $source.'.png';

Comments

0
foreach(item_category()) as $category) { 
    $source .= $category->cat_name; 
}

echo $source'.png';

this should output

cat1cat2cat3.png

Comments

0

The quick answer is to put this line

echo $source.'.png';

Outside your foreach loop.

Comments

0
foreach(item_category() as $category) { 
    echo $category->cat_name; 
}
echo '.png';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.