Let's say I have code as follows: foreach($cat as $index => $value) { if($cat1 == $index || $cat2 == $index || $cat3 == $index || $cat4 == $index || $cat5 == $index) { echo ' <a href="/directory/'.$index.'/">'.$value[2].'</a> '; } } Code (markup): This code will output UP TO 5 hyperlinks in one line, depending on which, if any values exist in the array. For example: Item1 Item2 Item3 Item4 Item5 I now need to present this in a better form, as follows: - Item1 | Item2 | Item3 | Item4 | Item5 The '|' separator should not appear after the last item, and it should not appear if there is only one item. The '-' seperator should only appear before the first item, if one exists. How do I do this?
foreach($cat as $index => $value) { if($cat1 == $index || $cat2 == $index || $cat3 == $index || $cat4 == $index || $cat5 == $index) { echo ' <a href="/directory/'.$index.'/">'.$value[2].'</a> '; } } change to: foreach($cat as $index => $value) { if ($cat1 == $index) { echo '- <a href="/directory/'.$index.'/">'.$value[2].'</a>'; } if ($cat2 == $index) { echo ' | <a href="/directory/'.$index.'/">'.$value[2].'</a>'; } if ($cat3 == $index) { echo ' | <a href="/directory/'.$index.'/">'.$value[2].'</a>'; } if ($cat4 == $index) { echo ' | <a href="/directory/'.$index.'/">'.$value[2].'</a>'; } if ($cat5 == $index) { echo ' | <a href="/directory/'.$index.'/">'.$value[2].'</a>'; } }
You can use the build in function of implode: $good_categories = array ($cat1, $cat2, $cat3, $cat4, $cat5) $final_arr = array(); foreach ($cat as $index => $value) { if (inarray($cat, $good_categories)) { $final_arr[] = '<a href="/directory/'.$index.'/">'.$value[2].'</a>'; } } echo implode(' | ', $final_arr); PHP: its a little more generic - you can now use a different number of categories without modifying alot of code
Thanks guys. The first solution seems rather long though, lot's of repetition going on there! Second solution looks rather complex for what I'm trying to acheive. As always, I like to keep my code as short and simple as possible! Surely there is a short and simple solution?