Compare explode array with select option text

1

How to compare Array of explode , with text of option . If it is the same, tick it with selected .

<?php
//header('Content-Type: application/json; charset=utf-8');
include 'config.php';

$rs2 = $conexao->query("SELECT * FROM tags WHERE id_subcategoria = '{$_GET['id']}' AND idioma = 'pt-br' ");

$rs3 = $conexao->query("SELECT habilidades FROM categoriasub WHERE ID_Subcategoria = '{$_GET['id']}' AND idioma = 'pt-br' ");
$row3 = $rs3->fetch_assoc();


$habilidades = explode(",", $row3['habilidades']);



while($row2 = $rs2->fetch_assoc()) {
    echo '<option value="'.$row2['ID_Tag'].'">'.$row2['tag'].'</option>';
}
?>

While result

<option value="1">PHP</option> 
<option value="2">MYSQL</option>
<option value="3">HTML</option>
<option value="4">Designer de site</option>

Array result $ skills

Array
(
    [0] => PHP
    [1] =>  HTML
    [2] =>  Designer de site
)
    
asked by anonymous 01.08.2017 / 21:53

1 answer

1

Compare the value that comes from the bank with the skill array with the function in_array() if find assigns $selected to the selected value. Then mount the template with printf() .

while($row2 = $rs2->fetch_assoc()) {
    $selected = in_array($row2['tag'],$habilidades) ? 'selected="selected"' : ''; 
    printf('<option value="%s" %s>%s</option>', $row2['ID_Tag'], $selected, $row2['tag']);
}
    
01.08.2017 / 22:04