Possible Duplicate:
Implode array with “, ” and add “and ” before last item
I'm customising a WordPress theme and I have created some checkboxes in the user profile page in the admin, 3 to be exact. When a user checks each box the value of that box is saved in an array calle $goals when they save their profile. This all works great.
On a template page I'm doing some tests on how to display certain content based on what goals the user has selected so I have created the following code which checks whether the array contains each value on it's own and then combinations of goals together and then echos specific content based on those selections. It works just fine but I feel the code is bloated and could be streamlined. This is something I'm always looking to do with my code. I would really appreciate your thoughts on how I can achieve the same results with less code. Thanks.
$goals = get_user_meta( $userID, 'goals', $single );
if (in_array('Weight Loss', $goals, true) && !in_array('Improve Fitness', $goals, true) && !in_array('Improve Health', $goals, true)) {
echo 'Weight Loss';
} elseif (in_array('Improve Fitness', $goals, true) && !in_array('Weight Loss', $goals, true) && !in_array('Improve Health', $goals, true)) {
echo 'Improve Fitness';
} elseif (in_array('Improve Health', $goals, true) && !in_array('Improve Fitness', $goals, true) && !in_array('Weight Loss', $goals, true)) {
echo 'Improve Health';
} elseif (in_array('Weight Loss', $goals, true) && in_array('Improve Fitness', $goals, true) && !in_array('Improve Health', $goals, true)) {
echo 'Weight Loss and Improve Fitness';
} elseif (in_array('Weight Loss', $goals, true) && !in_array('Improve Fitness', $goals, true) && in_array('Improve Health', $goals, true)) {
echo 'Weight Loss and Improve Health';
} elseif (!in_array('Weight Loss', $goals, true) && in_array('Improve Fitness', $goals, true) && in_array('Improve Health', $goals, true)) {
echo 'Improve Fitness and Improve Health';
} elseif (in_array('Weight Loss', $goals, true) && in_array('Improve Fitness', $goals, true) && in_array('Improve Health', $goals, true)) {
echo 'Weight Loss, Improve Fitness and Improve Health';
} else {
echo 'Nothing set';
}