Checkbox with PHP

Asked

Viewed 115 times

-1

The site has 3 checkbox, but I will implement much more. The problem is that my code is not very cool, because I need to calculate the total value

Code is like this:

$hena = filter_input(INPUT_POST, "hena", FILTER_SANITIZE_MAGIC_QUOTES);
$simples = filter_input(INPUT_POST, "simples", FILTER_SANITIZE_MAGIC_QUOTES);
$maquiagem = filter_input(INPUT_POST, "maquiagem", FILTER_SANITIZE_MAGIC_QUOTES);

$valorHena = 20; // Valor da Hena
$valorSimples = 15; // Valor da Simples
$valorMaquiagemIndividual = 100; // Valor da maquiagem individual

if (isset($hena) && !isset($simples) && !isset($maquiagem)) {
        $dado->setResultado($valorHena);
    }elseif (isset($simples) && !isset($hena) && !isset($maquiagem)) {
        $dado->setResultado($valorSimples);
    }elseif (isset($maquiagem) && !isset($hena) && !isset($simples)) {
        $dado->setResultado($valorMaquiagemIndividual);
    }elseif (isset($hena) && isset($simples) && !isset($maquiagem)) {
        $resultado = $valorHena + $valorSimples;
        $dado->setResultado($resultado);
    }elseif (isset($hena) && isset($maquiagem) && !isset($simples)) {
        $resultado = $valorHena + $valorMaquiagemIndividual;
        $dado->setResultado($resultado);
    }elseif (isset($maquiagem) && isset($simples) && !isset($hena)) {
        $resultado = $valorMaquiagemIndividual + $valorSimples;
        $dado->setResultado($resultado);
    }elseif (isset($maquiagem) && isset($simples) && isset($hena)) {
        $resultado = $valorHena + $valorSimples + $valorMaquiagemIndividual;
        $dado->setResultado($resultado);
    }

As you can see it’s quite confusing, wanted to get better and tried everything someone could give a hint ?

  • The way we’re seeing it is not confused, it’s impossible to understand, kkkk, but getting this code I don’t see why you want to improve. I ask: is it working well? If it is then good!

  • kkk yes it works however this code is that I will have to increment more than 10 elseif.

  • has the switch case that tb will give the same trouble

  • has how you click edit in my answer, copy and paste in your question

  • I also thought of the switch However in the case part I would need to pass 2 information at the same time and I do not know how to :/

  • is boy, with 10 more inputs will give a work even if Else. I’m thinking here a way to put in an array

  • You have a sense of how you would do that?

  • Hello, this looks like code review.

  • I know you’re trying to help relax. I’ll try to find a way if I get a code cuter kk I put here so other people see it too

  • Leo, I found a solution, but I don’t know if it’s good or bad, but it’s a good one. Is ternary $result = (isset($hena))? $result + $valueHena : $result; $result = (isset($simple))? $result + $valueSimples : $result; $result = (isset($makeup))? $result + $valueIndividual : $result;

  • Boy, I woke up late and already put an answer using array, kkk, Who goes to sea loses its place and who goes to the wind loses its seat. ;)

Show 6 more comments

3 answers

1

I will demonstrate two ways to improve this, one easier to understand (using explicit loops) and another using array manipulation functions, in the end both achieve the same goal. Both allow you to add and remove items without the need to change or add comparators/conditions to the code by just adding an item to the array.


First in both cases define an array of values:

$valoresProdutos = [

    'Hena' => 20,
    'Simples' => 15,
    'MaquiagemIndividual' => 100

];

Then you’ll need to add up the figures:

/*1*/ $produtosEscolhidos = $_POST;

/*2*/ $valoresEscolhidos = array_intersect_key($valoresProdutos, $produtosEscolhidos);

/*3*/ $valoresSomados = array_sum($valoresEscolhidos);

/*4*/ echo $valoresSomados;

TEST THIS OUT HERE.

If you want "all in one line":

echo $valoresSomados = array_sum(array_intersect_key($valoresProdutos, $_POST));

Translating what is done:

  1. The $produtosEscolhidos has all the information from $_POST, array, thus if the body of the POST for Hena=Qualquer_Coisa&Simples=ABC then the array will be array( "Hena" => "Qualquer_Coisa", "Simples" => "ABC" ).

You could also use $produtosEscolhidos = array_flip(array_keys($_POST)) to make clear that what matters would be the key and not the values, the array_keys get the keys to the POST, this will generate something like ([0]=> "Hena"), but we need the Hena as a key and not a value, for this we use the array_flip and then this will stay ["Hena"]=> 0.

  1. The array_intersect_key returns all array values $valoresProdutos which have keys equal to the $produtosEscolhidos, so if selected only "Hena" will be ["Hena"]=> 20 and if you select "Hena" and "Simple" you will be ["Hena"]=> 20, ["Simples"]=> 15, remembering that this is case-sensitive.

  2. Finally we use the array_sum to sum up the values of $valoresEscolhidos, so we added everything that was selected by the user.

  3. The echo was used only to show the result.


As I said it is possible to do this without the need to use these functions, after all maybe you do not know them or think it is complex, I believe that the important thing is to understand how it works (I recommend you to read the documentation) instead of giving a CTRL+C and CTRL+V. Anyway, we can use the foreach and check whether or not the user selected that item.

$valoresSomados = 0;

foreach($valoresProdutos as $_nomeProduto => $_valorProduto){

    if( isset($_POST[$_nomeProduto]) ){
        $valoresSomados += $_valorProduto;
    }

}

echo $valoresSomados;

TEST THIS OUT HERE

I believe in this case is self-explanatory, you have the $valoresSomados initially 0, then he gets the list $valoresProdutos and checks if the user has selected (i.e. if any $_POST['Hena'] is because the user selected), so we added the price of "Hena" to the $valoresSomados.


You could also generate the checkbox as follows:

$valoresProdutos = [

    'Hena' => 20,
    'Simples' => 15,
    'MaquiagemIndividual' => 100

];

echo '<form action="sua_pagina.php" method="post">';

foreach($valoresProdutos as $_nomeProduto => $_valorProduto){

    echo '<label>';
    echo    '<input type="checkbox" name="'.$_nomeProduto.'" value="true">';
    echo    $_nomeProduto;
    echo '</label>';

    echo '<br>';
}

echo '<input type="submit" name="Enviar">';

echo '</form>';

So automatically when added a new item in array would exist in a new checkbox. Another option would be to create functions that create HTML, for example.

  • Great Inkeliz, is giving error: PHP Parse error: syntax error, Unexpected '[' in..... on line 3. Line 3 is $valuesProducts = [

  • What is your version of PHP? It’s smaller than PHP 5.4?! If you are, you’ll have to switch to PHP array( and then ), instead of [ and ]. Try to upgrade this to a newer version, if possible, this is very old, PHP 5.3 was discontinued in August 2014.

  • Hummm, and if you use array( ...); in current versions it will work?

  • I put this $productsChooded = array_flip(array_keys($_POST)) and it only brings so [0] => 'hena' the way you said it is mto good until it saves code but I could not do :/

  • @Leocaracciolo yes, the array() is compatible with all versions.

  • @heitor_deep, use the array_flip(array_keys($_POST)) you still need to use the rest of the code, this will only cause the values to be removed (for example hena=QualquerCoisa stay hena=0), in practice there is no difference between the two, just makes it clear that you are interested in the Dexes and not in the values, if you in the future see the code, the array_keys() will already point to you "this picks up the keys", while the $_POST you know it has all the content. The $valoresSomados = array_sum(array_intersect_key($valoresProdutos, $_POST)); does everything. ;)

  • @Inkeliz - My thought: The ideal is an answer that would suit everyone in the community!!!

Show 2 more comments

0

I believe that in the following way it would already simplify enough:

$isHena = isset($hena); 
$isSimples = isset($simples); 
$isMaquiagem = isset($maquiagem);
$resultado = $isHena * $valorHena + $isSimples * $valorSimples + $isMaquiagem * $valorMaquiagem;
$dado->setResultado($resultado);

Because the value of isset will return true or false, that will be 0 or 1 in multiplication.

0

Galera managed to solve my problem follows the code below

<?php

  if (isset($_POST['ok'])) {
      // checkbox ta assim name="servico[simples] servico[hena]...." no value ta o valor total.
$servicos = $_POST['servico'];
// Devino os valores aqui
$post = array(
    'servico' => array(
        0 => 15,
        1 => 20,
        2 => 100,
        3 => 30,
        )
);

if (!empty($servicos)){
    $variavel = "";
    foreach ($servicos as $campo => $valor) {
          // pego o nome (hena,simples, blábáblá)  
        $variavel .= $campo . ' ';      
        // soma de todos os checkbox que foi digitado
        $re = array_sum($servicos);

    }
    // apartir daqui jogo no setter e mando bala.
   echo $re . '<br/>';
   echo $variavel;


}else{
    echo "não foi passado";
}
}

?>

Browser other questions tagged

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