Seemingly Simple ForEach Loop Problem..

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jjk215
Forum Newbie
Posts: 2
Joined: Thu Jul 01, 2010 2:57 pm

Seemingly Simple ForEach Loop Problem..

Post by jjk215 »

Hello everyone. Im working on a Wordpress site and ran into a problem trying to display some information in a foreach loop. I have very remedial PHP skills and have searched far and wide for the answer and cant seem to get it. I found a way to customize the way my categories are displayed and found this chunk of code online and it works perfectly.

Code: Select all

<?php 
foreach((get_the_category()) as $childcat) 
{ 
     if (cat_is_ancestor_of(10, $childcat)) 
        { 
        echo '<a href="'.get_category_link($childcat->cat_ID).'">'; echo $childcat->cat_name . '</a>' . ', '; 
        }
}
 ?>
The only problem is the trailing comma at the end of the loop. It displays like 'Categories: Category 1, Category2, Category 3,'.
I got the closest using substr but it deleted all of the comma's, not just the last one. Here is the code I used for that:

Code: Select all

<?php 
foreach((get_the_category()) as $childcat) 
{ 
if (cat_is_ancestor_of(10, $childcat)) 

        {
	$str = '<a href="'.get_category_link($childcat->cat_ID).'">' . $childcat->cat_name . '</a>' . ', '; 
	substr($str, 0, -2); echo $str;
	}
	
} ?>
All I want is for this to display 'Categories: Category 1, Category 2, Category 3' like the regular wordpress category function does. Any help is very very much appreciated!
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Seemingly Simple ForEach Loop Problem..

Post by AbraCadaver »

I might do it like this:

Code: Select all

foreach((get_the_category()) as $childcat)
{
     if (cat_is_ancestor_of(10, $childcat))
        {
        $cats[] = '<a href="' . get_category_link($childcat->cat_ID) . '">' . $childcat->cat_name . '</a>';
        }
}
echo implode(', ', $cats);
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
jjk215
Forum Newbie
Posts: 2
Joined: Thu Jul 01, 2010 2:57 pm

Re: Seemingly Simple ForEach Loop Problem..

Post by jjk215 »

You're the man! :drunk:
Post Reply