I have a variable post value and I would like to find it. For that I have a for loop and I'm trying to get the post data like that
$_POST['discount'.$i]
But when I echo it I get discount.$i
instant of the value. What is wrong?
for ($i=0; $i<10;$i++){
if(isset($_POST['discount'.$i]) && isset($_POST['percentage'.$i])){
$discount[$i] = $_POST['discount'.$i];
$percentage[$i] = $_POST['percentage'.$i];
echo '$discount.$i';
echo '$percentage.$i';
}
}
Use like
for($i = 0; $i < 10; $i++)
{
if(isset($_POST['discount' . $i]) && isset($_POST['percentage' . $i]))
{
$discount[$i] = $_POST['discount' . $i];
$percentage[$i] = $_POST['percentage' . $i];
echo $discount[$i]."<br>";
echo $percentage[$i]."<br>";
}
}
As i comment
do this in two steps: $s = 'discount'.$i; echo $_POST[$s]
and has a feedback of 3 votes, I make an answer, and got downvotes, I know the reason of downvotes, Now i make complete answer.
You need to make this two steps. First store in a variable and use the variable inside the $_POST
.
for ($i=0; $i<10;$i++){
$discounts = 'discount'.$i;
$percentages = 'percentage'.$i;
if(isset($_POST[$discounts]) && isset($_POST[$percentages])){
$discount[$i] = $_POST[$discounts];
$percentage[$i] = $_POST[$percentages];
}
}
Variables don't expand inside single quotes (echo '$discount.$i'
) and you need to echo the array value $discount[$i]
not $discount.$i
.isset()
allows empty values I would use !empty()
instead, something like:
for ($i=0; $i<10;$i++){
if(!empty($_POST["discount$i"]) && !empty($_POST["percentage$i"])){
$discount[$i] = $_POST["discount$i"];
$percentage[$i] = $_POST["percentage$i"];
echo $discount[$i];
echo $percentage[$i];
}
}