Get total [checkbox] value - php

HTML:
<input type="checkbox" name="product[book]" value="10" /> book
<input type="checkbox" name="product[plane]" value="20" /> plane
PHP:
foreach ($_POST['product'] as $name => $value) {
echo $value;
}
How to get the total (sum) value if the user select two fields (book & plane)

You can use array_sum:
$sum = array_sum(array_map('intval', $_POST['product']));
Assuming you already checked validity of the $_POST['product'] field.

In your form you have an array of product. If you foreach that, create a $total = 0; at the start, add the value to it, at the end you have a total.
You can check that would work by print_r($_POST) and you'll see any selected values show as part of an array within the array of $_POST.

try
$total=0;
foreach ($_POST['product'] as $k) {
$total +=$k;
}
echo $total;

$pTotal = 0;
foreach ($_POST['product'] as $pVal)
{
$pTotal += intval($pVal,10);
}
Make sure you're explicit about the format type. Without checking, I would expect the values coming in to be strings, not integers... which will give you all sorts of headaches if you're trying to add them up. : )

Related

How to delete last value in foreach loop

I have a dynamic multi input. When submit form, inserting array values. But I want to insert without 'submit' value.
This is the foreach loop, (sql secure not included)
if (isset($_POST['submit'])) {
$nearest = $db->prepare('insert into nearest set place=?, distance=?');
$i = 0;
foreach ($_POST as $val) {
$place = $_POST['place'][$i];
$distance = $_POST['distance'][$i];
$nearest->execute([$place, $distance]);
$i++;
}
}
This loop inserted '$_POST' values and inserted empty row.
If you want to keep the loop you can use array_slice to not include the last item in the loop.
Array_slice will take items from 0 (not literal, but the first item) to second to last (-1).
http://php.net/manual/en/function.array-slice.php
EDIT; I think you need a for loop to loop the count of "place".
if (isset($_POST['submit'])) {
$nearest= $db -> prepare('insert into nearest set place=?, distance=?');
for($i=0; $i< count($_POST['place']; $i++){
$place = $_POST['place'][$i];
$distance= $_POST['distance'][$i];
$nearest-> execute([$place , $distance]);
$i++;
}
}
example: https://3v4l.org/F47ui
You can simply remove your submit key from $_POST prior doing your loop with just regular unset(). But this is bad approach. What I'd rather recommend doing instead is to "isolate" your data, and instead of this:
<input name="distance" ... >
make all your imputs like this:
<input name="data[distance]" ... >
then you just need to loop over "data" (name as you like) array:
foreach($_POST['data'] as val)
Also, resist from removing last element in blind, because it's based on false assumption that this is always your "submit" element. What if you add more submit buttons to the form? or the order will change?

submit form data from a foreach loop

I have a foreach loop with a form inside for each result like so:
foreach($this->results() as $that) {
<form>
<input type="text" name="name[]">
<input type="text" name="this[]">
</form>
}
and so on. My question is how do I each forms data. I understand you can do something like the following:
$_POST['name'][0];
$_POST['name'][1];
etc, but is their a way to get this done without knowng how many forms their will be. I mean like foreach loop the $_POST data and get each form?
Many thanks
foreach ($_POST['name'] as $val) { /* do what you want, want you want with my value */ }
$_POST['name'] is just an array. Use count or any array function you want on it then.
You can do it like this:
foreach ($_POST['name'] as $val => $value) {}
assuming these rows are being generated by a while loop, and the variable is named like this
$val = $row['val'];
And then in your form you'd have something like this:
echo '<input type="hidden" value="'.$val.'" name ="val[]" /><input type="text" name="name['.$val.'] />";
basically the name variable would be identified by the value itself being generated but also appended on a named variable, and then can be fed into your foreach.
foreach ($_POST['name'] as $key => $value) {
echo 'key: '.$key.' Value : '.$value;
}
--------------------------
output key: 0 Value : nameValue1
key: 1 Value : nameValue2
$_POST['name'] is an array, if you get multiple value with key, just get with foreach value

$_POST metacharacters?

in my $_POST, I have a variable whose name changes. the name is modify_0, but the number at the end changes depending on the button that was pressed.
Is there anyway to check what the number is for that variable in $_POST?
Say:
$_POST['modify_(check for number or any character)']
You would need to iterate over all of the keys within the $_POST variable and take a look at their format:
$post_keys = array_keys( $_POST );
foreach($post_keys as $key){
if ( strpos($key, 'modify_' ) != -1 ){
// here you know that $key contains the word modify
}
}
Besides the correct answers given above, I would recommend changing your code slightly so it's easier to work with.
Instead of having inputs with the format:
// works for all types of input
<input type="..." name="modify_1" />
<input type="..." name="modify_2" />
You should try:
<input type="..." name="modify[1]" />
<input type="..." name="modify[2]" />
This way, you can iterate through your data in the following way:
$modify = $_POST['modify'];
foreach ($modify as $key => $value) {
echo $key . " => " . $value . PHP_EOL;
}
This works especially well for multiselects and checkboxes.
Try something like this:
// First we need to see if there are any keys with names that start with
// "modify_". Note: if you have multiple values called "modify_X", this
// will take out the last one.
foreach ($_POST as $key => $value) {
if (substr($key, 0) == 'modify_') {
$action = $key;
}
}
// Proceed to do whatever you need with $action.

Get the ids and loop through post data

I post a form with the same input names+id at the end like that:
<input type="text" name="machine_1">
<input type="text" name="machine_11">
<input type="text" name="machine_23">
How loop through on each of them and get the id's in the loop?
I tried this way, but it will loop a lot without any data and what happens if there is more thank 100 id?
for($i=0; $i<100; $i++){
$_POST["machine"]=$_POST["machine_".$i];
$id=$i;
}
POST is an associate array, so you can loop through everything that's been posted like this:
//$k contains the id
//$v contains the submitted value
foreach($_POST as $k => $v) {
//test if id contains 'machine'
if(stristr($k, 'machine')) {
echo $v;
}
}
You can do this using a foreach loop, like so:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value';
}
$_POST["machine"]=$_POST["machine_".$i];
here $_POST['machine'] represents noting..how can you assign a value to $_POST['machine']..you havent passed any element having name machine while submitting the form..so first of all you need to check it bro
In your code, you have:
$_POST["machine"]=$_POST["machine_".$i];
That's not the correct way. You want to store the value of $_POST["machine_".$i] to $id and then use it below.
This is probably what you need:
for($i=1; $i<100; $i++){
$id = $_POST["machine_".$i];
echo $id;
}
And if there are more than 100 elements, and you don't know the number of inputs, then you can use a foreach loop, as below:
$i = 1; // counter variable
foreach ($_POST as $key => $input) {
if($key == "machine_".$i) {
$id = $input; // or simply 'echo $input'
echo $id;
}
$i++; // increment counter
}

How to use foreach loop in order to get whole block of information related to criteria: "is greater than"?

Does anyone know how to use FOREACH loop in order to get whole block of information related to criteria: "is greater than" the number posted by user (in this case $metsq=$_POST['metersq'];)
For example, in code I posted, if user write 90, it should outputs only
color - blue
msq - 100
city - Prague
I tried this code, but, obviously, I don't have much experience.
Thanks in advance!
<?php
if(isset($_POST['button'])){
$houses = array(
'house1'=>array(
'color'=>'green',
'msq'=>100,
'city'=>'Prague'
),
'house2'=>array(
'color'=>'red',
'msq'=>30,
'city'=>'Belgrade'
),
'house3'=>array(
'color'=>'blue',
'msq'=>50,
'city'=>'London'
),
'house4'=>array(
'color'=>'blue',
'msq'=>50,
'city'=>'Belgrade'
)
);
$col=$_POST['colors'];
$metsq=$_POST['metersq'];
$cit=$_POST['cities'];
foreach($houses as $house=>$data) {
foreach($data as $key=>$value) {
if($value>=$metsq) {
echo "$key - $value </br>";
}
}
} else {
echo "Go, search";
}
?>
<form action="?" method="post">
<select name="colors" >
<option>green</option></br>
<option>blue</option></br>
<option>red</option></br>
</select>
<input type="number" name="metersq" id="metersq" maxlength="3" />m2</br>
<select name="cities">
<option>Prague</option></br>
<option>Belgrade</option></br>
<option>London</option></br>
</select>
<input type="submit" value="Find" name="button"id="button" />
It looks like you want to output the entire house1 as a set of key/value pairs.
You're pretty close:
foreach($houses as $house=>$data){
if( $data['msq'] >= $metsq ) {
foreach( $data as $key=>$value ) {
echo "$key - $value <br>";
}
}
}
The problem you were having is that you were really only outputting data when the specific key met your conditional. But you were making comparisions like blue >= 90 which could have unexpected results.
Instead of looping through the house data, just loop through the 'msq' keys:
foreach($houses as $house){
if($house['msq']>=intval($metsq)){
echo "msq - {$house['msq']} </br>";
}
}
Also, you might need to make sure that they are integers, with intval.
You don't need nested foreach loops. You just need to compare the msq key in each house element of the array like this:
foreach($houses as $house=>$data){
if ($data['msq'] >= $metsq) {
// found a matching house so do something with it
var_dump($house, $data);
}
}

Categories