conan conan - 4 months ago 8
HTML Question

How should I create global function base on this situation php?

I have a

if()
code will be so long, and some of them share some common html code. I think the better way is that call each html question base on the if condition. Look at my code, ex. if fruit=apple, I want to echo the html code question 1,3,5. How should I make the global function for the questions?

<?php
if(fruit=='apple'){
/*call question 1,3,5*/
}else if(fruit=='banana'){
/*call question 1,2,4*/
}/*.........a lot of else if.....*/

/*question
1. <div>Is it good?</div>
.............some multiple choice here
<input type="text" value="submit"/>
2. <div>where is it from?</div>
.............some multiple choice here
<input type="text" value="submit"/>
3. <div>...........</div>
.............some multiple choice here
<input type="text" value="submit"/>
4. <div>..........</div>
.............some multiple choice here
<input type="text" value="submit"/>
*/

?>

Answer

You could write your code like this:

$fruit = "apple";

if (in_array($fruit, ["apple", "banana"])) {
    echo '<div>Is it good?</div>
       .............some multiple choice here
       <input type="text" value="submit"/>';
}
if (in_array($fruit, ["banana", "pineapple"])) {
    echo '<div>where is it from?</div>
       .............some multiple choice here
       <input type="text" value="submit"/>';
}
// etc...

There are of course other ways to do it. You could build a data structure giving you all the information you need, including the HTML, and then with a just a small loop to output the selected HTML:

$fruit = "apple";

$questions = array(
    "1" => array(
        "question" => "Is it good?",
        "answers" => ["Fantastic", "So-so", "Never again"]
    ),
    "2" => array(
        "question" => "Where is it from?",
        "answers" => ["South America", "Africa", "Australia"]
    ),
    "3" => array(
        "question" => "Which color does it have",
        "answers" => ["Yellow", "Red", "Orange"]
    ), //...etc
);
$questionsForFruits = array(
    "apple" => [1, 3],
    "banana" => [1, 2],
    "pineapple" => [2]
);

$fruit = "apple";

foreach($questionsForFruits[$fruit] as $questionNo) {
    $q = $questions[$questionNo];
    echo "<div>{$q['question']}</div>
          <select>";
    foreach($q['answers'] as $index =>$answer) {
        echo "<option value = '$index'>$answer</option>";
    }
    echo "</select><br>
          <input type='text' value='submit'/>";
}
Comments