<input type="checkbox" name="item[]" value="HairCut" /> <br />
<input type="checkbox" name="item[]" value="HairColor" />
<button name="submit" type="submit">Print</button>
<?php
if(isset($_POST['submit'])){
if(empty($_POST['item'])){echo "Please Select Atleast One Option";}
else {
if(in_array('HairCut', $_POST['item'])){$name = "Hair Cut";}
if(in_array('HairCut', $_POST['item'])){$price = "20";}
if(in_array('HairColor', $_POST['item'])){$name = "Hair Color";}
if(in_array('HairColor', $_POST['item'])){$price = "30";}
echo "$name:$price <br>";
}
}
?>
If i check both checkbox together then i get only single result like
Hair Color:30
But expectation result is both like
Hair Cut:20
Hair Color:30
Anyone able to help me regarding this issue?
You are only echoing once! And also you may like to optimise your if loops as below:
<?php
if(isset($_POST['submit'])){
if(empty($_POST['item'])){
echo "Please Select Atleast One Option";
} else {
if(in_array('HairCut', $_POST['item'])){
$name = "Hair Cut";
$price = "20";
echo "$name:$price <br>";
}
if(in_array('HairColor', $_POST['item'])){
$name = "Hair Color";
$price = "30";
echo "$name:$price <br>";
}
}
}
?>
You could try something along these lines perhaps where you have a predefined array of options with associated values and test if an item exists in the submitted data in order to display the item and price.
if( isset( $_POST['submit'], $_POST['item'] ) && !empty( $_POST['item'] ) ){
$matrix=array(
'haircut' => 20,
'haircolor' => 30,
'beardtrim' => 5,
'shave' => 10
);
$total=0;
foreach( $_POST['item'] as $item ){
$key = strtolower( $item );
if( array_key_exists( $key, $matrix ) ){
echo "$item: {$matrix[ $key ]}<br />";
$total += floatval( $matrix[ $key ] );
}
}
echo "<br /><br />Total: {$total}";
} else {
if( empty( $_POST['item'] ) ){
echo 'Please select at least one option';
}
}