Forum Moderators: coopster
This is hard to explain, I think. I have a form where the end user selects from a list. There's three questions, and they have several choices in each question. Based on the answers to these three questions (if any answers are made), then a list should be created. If one answer is made, then the list should consist of one format. But if two, or all three questions are answered, then the format changes.
So, to keep it simple, say the form questions are fruits, vegetables and animals. Under fruits, you could choose "apples", "oranges", "bananas" or grapes". Veg could be "carrots", "celery", "onions" or "potatoes". Animals would be "dogs", "cats", "fish" or "birds".
Now, say the end user didn't answer #1 (fruits), but answered "carrots" for #2 and "cats" for #3.
The resulting line should read:
( (carrots) ¦¦ (cats) )
if he also answered #1 with "oranges", then the line would be:
( (oranges) ¦¦ (carrots) ¦¦ (cats) )
See where I'm going with this?
I've tried my own hand at this, but I am failing utterly. What *I* have is this:
$var = array('fruit', 'vegetable', 'animal');
foreach ($item AS $v) {
$var[] = "($v!= $something)";
}
if (count($var) > 0) {
$output = implode(' ¦¦ ', $var);
} else {
$output = '';
}
However, I keep getting an error message that an "invalid argument is supplied foreach()". I'm guessing it's because I don't know what $something should be. It could also be that my code is utterly whacked. But I'm having a block at to what $something should actually be - and then maybe I can have it do what I want it to do.
Can anyone pass me a clue?
on edit added:
Actually, if you wanted something a bit more elegant:
$answers = array();
if($fruits!= '')
$answers[] = $fruits;
if($veg!= '')
$answers[] = $veg;
if($animal!= '')
$answers[] = $animal;
if(count($answers) > 1)
$theanswer = '(' . implode(') ¦¦ (',$answers) . ')';
else
$theanswer = "({$answer[0]})";
The only thing I had to change was the "if(count($answers) > 1) {" - because if only *one* selection was made, it wouldn't output anything at all. When I changed that "1" to "0", it would output the one thing, just as I needed it to, but it would also add the "¦¦" where I needed it if *more* than one answer was given.
Thank you so much - I really appreciate it!
$theanswer = '(' . join(') ¦¦ (', [url=http://us3.php.net/array_filter]array_filter[/url](array($fruits, $veg, $animal))) . ')'; Or, if you want to keep the array of answers around:
$answers = array_filter(array($fruits, $veg, $animal));
$theanswer = '(' . join(') ¦¦ (', $answers) . ')'; Then, as you might imagine, adding "Color" and "Meat" fields doesn't require copying and pasting several lines of code each.