I often need to list items separated by comma, space or punctuation, addresses are a classic example (This is overkill for an address and is for the sake of an example!):
echo "L$level, $unit/$num $street, $suburb, $state $postcode, $country.";
//ouput: L2, 1/123 Cool St, Funky Town, ABC 2000, Australia.
As simple as it sounds, is there an easy way to "conditionally" add the custom separators between variables only if the variable exists? Is it necessary to check if each variable is set? So using the above, another address with less detail may output something like:
//L, / Cool St, , ABC , .
A slightly arduous way of checking would be to see if each variable is set and display the punctuation.
if($level){ echo "L$level, "; }
if($unit){ echo "$unit"; }
if($unit && $street){ echo "/"; }
if($street){ echo "$street, "; }
if($suburb){ echo "$suburb, "; }
//etc...
It would be good to have a function that could automatically do all the stripping/formatting etc:
somefunction("$unit/$num $street, $suburb, $state $postcode, $country.");
Another example is a simple csv list. I want to output x items separated by comma:
for($i=0; $i=<5; $i++;){ echo "$i,"; }
//output: 1,2,3,4,5,
In a loop for example, what's the best way of determining the last item of an array or the loop condition is met to not include a comma at the end of the list? One long way around this I've read of is to put a comma before an item, except the first entry something like:
$firstItem = true; //first item shouldn't have comma
for($i=0; $i=<5; $i++;){
if(!$firstItem){ echo ","; }
echo "$i";
$firstItem = false;
}