Concatenate array of selected checkboxes to use as search filter

2

I have a search with several checkboxes that can be selected and added dynamically by the user. As I do not know the quantity, I was thinking of doing the following: go through all of them and go concatenating with AND and use that in the condition there in the search.

The problem is that the way I did it ends up getting a AND alone at the end of the search. Here is my code:

$Busca = $_POST['txtbusca'];
$arrayFiltro = $_POST['chkDisciplina'];

for ($i=0; $i < count($arrayFiltro); $i++) { 
    echo $arrayFiltro[$i]. "AND";
}

Is there a better way?

    
asked by anonymous 08.06.2014 / 05:45

2 answers

7

The function implode() was done for this:

$separador = ' AND ';
$array = array( 'nome', 'email', 'fone' );
$string = implode( $separador, $array );
var_dump( $string );

Results in:

  

string (28) "name AND email AND phone"

    
08.06.2014 / 11:14
1

In the meantime, try to do this, you check, if the control variable $ i is less than the size of the array, you can add the AND at the end, if the variable is equal to the size of the array, is the last element, so it does not need AND, so it falls into the else.

$Busca = $_POST['txtbusca'];
$arrayFiltro = $_POST['chkDisciplina'];
$sql = "SELECT * suatabelela WHERE = ";
for ($i=0; $i < count($arrayFiltro); $i++) { 
    if($i<count($arrayFiltro) {
          $sqlAND .= $arrayFiltro[$i]. "AND";
    } else {
    $sqlAND .= $arrayFiltro[$i];
    }
}
    
08.06.2014 / 06:26