Search for record in array()

Asked

Viewed 44 times

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 the selected objects or 1 or 2, it always displays one missing. Example, if I search by id 2,3,6 it only comes to 3 and 4. 2 no longer displays. is always the first id that does not compare.

How to adjust this?

On the whole 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>
  • What is $listagem_area?

  • 1

    The array_search returns the found array key, if it is 0 the if will understand how false (due to poor PHP typing). So you should use array_search($valor->are_id, $are_id) !== false, This is one of the mistakes. Actually, I could use in_array() or could use the array_intersect() to get the common values in both arrays.

1 answer

1


This is probably due to weak PHP typing, array_search returns the key of the array 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 the array_search(1, [1,2,3]) is 0 which will be "converted" to a Boolean as 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 the ===). In this condition it exists. If there is no array_search returns false and in this case false === false so there is no.

Test this.

  • Perfectly @Inkeliz thank you, that was it. And I understood also your explanation, simple and objective. Grateful!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.