Reputation: 4995
I have a form that looks like this.
<form action="index.php" method="post">
<select name="dropdownOption">
<option value="First Choice +200">First Choice</option>
<option value="Second Choice +300">Second Choice</option>
</select>
<p><input type="checkbox" value="Rocket +100"> Rocket</p>
What I want to do is loop through every value sent in the _POST and then sum up every number after the '+' sign into a variable in the index.php file.
So for example if they chose the 'Second Choice' and ticked the 'Rocket' Checkbox it should add up to 400 (300+100).
In this example there is only two different options but in the final application there will be 20-30 different things that can vary which is why looping is necessary.
Also How can I loop through every element that is not hidden (so exclude hidden form elements).
Upvotes: 0
Views: 808
Reputation: 8446
Why wouldn't you drop the text in the values, and keep only numeric data? The values aren't visible anyway, but in your code, you can easily map the numeric values to the text. In other words, you can have something like this:
$choices = array(
'1' => array('value' => '100', 'text' => 'First choice'),
'2' => array('value' => '150', 'text' => 'Second choice'),
'3' => array('value' => '250', 'text' => 'Third choice'),
);
And display the data like this (or any other way, but having the ids of choices in the value field):
<form action="index.php" method="post">
<select name="dropdownOption">
<?php foreach($choices as $id => $choice): ?>
<option value="<?php echo $id ?>"><?php echo $choice['text']; ?></option>
<?php endforeach; ?>
</select>
</form>
And then having the initial array, you can easily sum up all the data:
$sum = 0;
foreach($selected as $id){
$sum += $choices[$id]['value'];
}
And display data to the user too:
<?php foreach($selected as $id): ?>
<p>You chose <?php echo $choices[$id]['text']; ?></p>
<?php endforeach; ?>
This is a way better approach as it gives you a lot of flexibility.
Upvotes: 0
Reputation: 1840
foreach ($_POST as $post) {
$num = explode('+', $post);
if (is_numeric((int) end($num)) {
$sum += end($num);
}
}
If you need negative values you can just make your option
look like this:
<option value="Second Choice +-300">Second Choice</option>
Upvotes: 1
Reputation: 2004
I'm considering you are storing the values sent using _POST in an array.
$total = 0;
foreach($selections as $sel){
$sep = $explode('+', $sel);
$value = (int)$sep[1];
$total += $value;
}
Upvotes: 1