Concatenate array of selected checkboxes to use as a search filter

Asked

Viewed 538 times

2

I have a search with several checkboxes that can be selected and added dynamically by the user. Since I don’t know the amount, I was thinking of doing the following: go through all of them and concatenate with AND and use it in the condition there in the search.

The problem is that the way I did it ends up being one AND alone at the end of the search. Follow my code:

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

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

There’s a better way?

  • Post your SQL that should be generated with this search filter?

2 answers

7


The function implode() was made 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"

  • 1

    And, if you prefer, you can also use Join()[http://www.php.net/manual/en/function.join.php], which is a nickname for implode();

  • The link I put in the comment above was "]" in the link, then follows without: http://www.php.net/manual/en/function.join.php

  • 1

    @Leofelipe, check out the comment formatting

  • Vlw @brasofilo. The next ones will be marked correctly!

1

Kind of gambiarra, but try this, you check, if the control variable $i is smaller than the size of the array, you can add the AND at the end, if the variable is equal to the size of the vector, it means it’s the last element, so you don’t need AND, then falls inside the Isis.

$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];
    }
}

Browser other questions tagged

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