Search whether or not there is a record in the array ()

0
$detalhes->pro_are_id = '["4","1","2","3","6"]'; // Dados foram gravados no banco atraés do json_encode()
$valor->are_id = 2;

if(!empty($detalhes) and isset($detalhes->pro_are_id)){ 
    $are_id = json_decode($detalhes->pro_are_id);
    if(array_search($valor->are_id, $are_id)){
        $existe = 1;
    }
}

The problem is that within the loop with all objects selected or 1 or 2, it always displays missing one. Example, if I search for id 2,3,6 it only comes 3 and 4. The 2 no longer displays. is always the first id that does not compare.

How to adjust this?

In the general set is this:

<p class="mb20">Selecione uma ou mais áreas</p>                         
<select id="select-multi" name="pro_are_id[]" data-placeholder="Escolha 1 ou +" multiple="" class="width300 select2-offscreen" tabindex="-1">
    <option>Selecione</option>
    <?php 
        $existe = 0;
        foreach($listagem_area as $valor){
            if(!empty($detalhes) and isset($detalhes->pro_are_id)){ 
                $are_id = json_decode($detalhes->pro_are_id);
                if(array_search($valor->are_id, $are_id)){
                    $existe = 1;
                }
            }                                               

    ?>
    <option value="<?php echo $valor->are_id; ?>" <?php if($existe==1) echo "selected"; ?> ><?php echo $valor->are_titulo; ?></option>
    <?php } ?>
</select>
    
asked by anonymous 21.05.2017 / 20:25

1 answer

1

This probably occurs because of poor PHP typing, array_search returns the array key that has the given value.

So consider this:

var_export( array_search(1, [1,2,3]) );
// 0

This is equivalent to doing:

if(0){
   echo 'Nunca será exibido :('; 
}

This is what happens because array_search(1, [1,2,3]) is 0 that will be "converted" to a boolean like false , the message will never be shown.

So change to:

if(array_search(1, [1,2,3]) !== false){
   $existe = 1;
}

In this case the 0 is different from false (using === ). In this condition it exists. If there is no array_search returns false and in this case false === false logo does not exist.

Try this.

    
21.05.2017 / 21:04