How to do a ternary <checkbox> check with PHP?

Asked

Viewed 538 times

0

I’m doing this field check <select> and everything is going well but I would like to do the same check on a <checkbox> who may have several possibilities then needing to work with arrays then I don’t know how to proceed.

Below the code I use for <select>:

PHP

if( isset( $_POST['valorminimo'] ) ) $_SESSION['valorminimo'] = $_POST['valorminimo'];

HTML

<option value="1mil" <?php echo (($valormaximo == '1mil') ? 'selected="selected"' : ""); ?>>1mil</option>

Now I have the code PHP down to the checkboxes that recovers the indexes correctly and need to know on HTML how to carry out a ternary verification to apply an effect on checked.

PHP

$dorms = isset( $_SESSION['dorms'] ) ? $_SESSION['dorms'] : array();

HTML

<input id="dorm1" class="hidden drm" type="checkbox" name="dorms[]" value="1" <?php ((in_array($dorms)) ? "checked='checked'" : "" ); ?>>                                   
<input id="dorm2" class="hidden drm" type="checkbox" name="dorms[]" value="2">                                  
<input id="dorm3" class="hidden drm" type="checkbox" name="dorms[]" value="3+">

In short: how to check on each input type checkbox if he is checked or not?

  • using foreach in $_POST['dorms'], checkboxes not selected or sent to the server (if I’m not mistaken)...

  • Can you demonstrate in a reply please?

  • I got lost a little, you want to do this client-side check (HTML) or server-side (PHP) because I do not see in your codes indications that these values go to the server...

  • I want to check on the return of PHP if these fields are "checked" ... take a look at this page that has the search and below the data returned from the search ... http://new.pier36imoveis.com.br/search

1 answer

2


Checkboxes that have not been checked will not be sent to the server, but depending on the context that this application works it is necessary to check the value of the checkbox, to avoid future inconvenience.

Assuming the name of the variable you gave var_dump be it $valores

if(isset($valores['dorms']) && is_array($valores['dorms']) && !empty($valores['dorms'])) { // verificações básicas
    foreach($valores['dorms'] as $key => $dorm) { // percorre a array
        if(!empty($dorm)) { // verifica se não está vazio
            echo 'O checkbox de índice ['.$key.'] e valor ['.$dorm.'] foi marcado';
        }
    }
}

and only...

  • I still don’t understand how to apply this to my code. What I sent to the server show the data was <?php echo "<pre>"; print_r($_SESSION); ?>

  • @Marcosvinicius Yes, in case it was only a substitute $valores for $_SESSION, or $valores = $_SESSION;

Browser other questions tagged

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