Joining with comma seperation

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
wasir
Forum Commoner
Posts: 49
Joined: Sun Jul 08, 2007 11:28 pm

Joining with comma seperation

Post by wasir »

I am trying to display list of items only they are available. If the variables are blank, I get
, , ,
How can I get the value only if it exists?

Code: Select all

 
if ($row['type'] == service) {
   echo 'service request';
} else {
   echo $row['type']; 
}
 
// incident
if ($row['break'] == yes) {
   $break = 'Break & Enter';
} else {
   $break = '';
}
 
if ($row['medical'] == yes) {
   $medical = 'Medical Emergency';
} else {
   $medical = '';
}               
 
if ($row['assault'] == yes) {
   $assault = 'Assault';
} else {
   $assault = '';
}           
                    
if ($row['claim'] == yes) {
   $claim = 'Insurance Claim';
} else {
   $claim = '';
}
                    
$incident = array($break, $medical, $assault, $claim);
$incident_comma = join(", ", $incident);
echo $incident_comma;
 
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Joining with comma seperation

Post by John Cartwright »

Code: Select all

if ($row['type'] == 'service') {
   echo 'service request';
}
 
$incident = array(); 
// incident
if ($row['break'] == 'yes') {
   $incident[] = 'Break & Enter';
} 
 
if ($row['medical'] == 'yes') {
   $incident[] = 'Medical Emergency';
}
 
if ($row['assault'] == 'yes') {
   $incident[] = 'Assault';
}         
                   
if ($row['claim'] == 'yes') {
   $incident[] = 'Insurance Claim';
}
                  
$incident_comma = join(", ", $incident);
echo $incident_comma;

Almost had it ;). Instead of adding all of the elements to the array, only add the ones that you want to use (as shown above). You also need to quote your strings (which I've taken the liberty to do for you).

Enjoy.
wasir
Forum Commoner
Posts: 49
Joined: Sun Jul 08, 2007 11:28 pm

Re: Joining with comma seperation

Post by wasir »

Thanks HEAPS.
:D
Post Reply