Forum Moderators: coopster

Message Too Old, No Replies

removing the last separator from the loop

         

hozyali

10:52 am on Apr 3, 2010 (gmt 0)

10+ Year Member



Hello,

I have this code


$catids = 'Humor, Travel, Tragedy,'; //this is how its found in the database.

$category = explode(",",$catids);
$catsize = sizeof($category);

// for loop to print the category names with separator (pipe)

for($i=0;$i<$catsize-1;$i++) {
echo $category[$i]. " | ";
}



The output of the above code is like this

Humor | Travel | Tragedy |


Now the problem is, I want the loop not to print the very last separator (pipe)

Is there a way to fix this?

Thanks

Readie

11:04 am on Apr 3, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



$catids = 'Humor, Travel, Tragedy, ';

$category = explode(", ", $catids);
$catsize = count($category);

for($i = 0; $i < $catsize - 1; $i++) {
if($i = ($catsize - 2)) {
$sep = ' | ';
} else {
$sep = '';
}
echo $category[$i] . $sep;
}

hozyali

11:17 am on Apr 3, 2010 (gmt 0)

10+ Year Member



not sure how to use it. I have a loop, and if I place it inside the loop, it removes all the pipes from the loop

Readie

11:21 am on Apr 3, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You can use rtrim after the loop if that's what you're refering to :), I've since edited my post though.

coopster

1:28 pm on Apr 3, 2010 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



$catids = 'Humor, Travel, Tragedy,'; //this is how its found in the database.

Is there a way to fix this?

Yes, don't write it to the database that way in the first place :)
Seriously though, data should be clean before being stored so if you manage the code that writes it to the database, you may want to address that maintenance program too.

As was stated, you can rtrim [php.net] the string first. There are other options too. preg_split [php.net] works a lot like explode [php.net] but offers more flexibility:
$category = preg_split('/,/', $catids, -1, PREG_SPLIT_NO_EMPTY); 
print implode(" | ", $category);
// Humor | Travel | Tragedy

hozyali

3:11 pm on Apr 3, 2010 (gmt 0)

10+ Year Member



thanks all for your help. I have fixed the issue.

when adding the values to the database, I removed the last comma by using substr.

Then on the code where I am retrieving, I removed the for loop and used implode instead. it worked perfect.

Thanks