2

How could I make this form suggest the words in the first column of $data?
This is what I'm trying but doesn't work. As you can see, I cannot make it run with <option value>

<?php

$data = '
Naranja:Orange
Manzana:Apple
Tomate:Tomato
Zanahoria:Carrot
Lechuga:Lettuce
Plane:Avión';


if($data && !empty($_GET['word'])) {
    $line = explode("\n", $data);
    for($i = 0; $i<count($line); $i++) {
        $item = explode(":", $line[$i]);
        if($_GET['word'] == $item[0]) { echo"<div>" . $item[0] . "</div> <div>" . $item[1] . "</div>"; break; }
    }
}


else {echo '

<form>
<input type="text" name="word" list="spanishlist" autocomplete="off">
<datalist id="spanishlist">
<option value="' . $item[0] . '">
</datalist>
</form>

';
}
?>
divibisan
  • 11,659
  • 11
  • 40
  • 58
Kathlyn
  • 233
  • 3
  • 12

1 Answers1

0
<?php

$data = 'Naranja:Orange
Manzana:Apple
Tomate:Tomato
Zanahoria:Carrot
Lechuga:Lettuce
Plane:Avión';

$pairs = explode("\n",$data);
$options = [];
$selected = '';
$html = '';
foreach($pairs as $pair) {
    $parts = explode(':', $pair);
    if (!empty($_GET['word']) && $_GET['word']==$parts[0]) {
        $html .= "<div>" . $parts[0] . "</div> <div>" . $parts[1] . "</div>";
    }
    $options [] = '<option value="' . $parts[0] . '">'; 
}
$html .= '<datalist id="fruits">';
$html .= implode($options);
$html .= '</datalist>';
$html .= '<input list="fruits">';

echo $html;
Amarnasan
  • 14,939
  • 5
  • 33
  • 37