I have several radiobutton arrays. They're named awardLevel0[] , awardLevel1[] , awardLevel2[], and so on, generated dynamically by the user. I want to know if this function will work to get their total sum values.
function awardCheck () {
$exist = true;
$num = 0;
$endsum = 0;
while ($exist)
{
$names = "awardLevel" . $num;
$awardLev = $_POST[$names];
if (empty($awardLev)) {
$exist = false;
return $endsum;
}
else
$endsum = $endsum + $awardLev;
$num++;
}
return $endsum;
}
When I run the code above, it gives me an error at $endsum = $endsum + $awardLev; saying i'm using unspported operand types. When I remove $awardLev, it runs without that error.
Is it possible to pass a variable containg a string to $_POST like
$postname = "awardLevel2";
$awardLev = $_POST[$postname];
Yes you can absolutely do that, but just a note:
With the []
syntax in the POST values, you get an array back rather than a string. You could use this to your advantage and even array_sum
the _POST[awardLevel]
values if you just drop the number, but I'm not sure if that would work for you.
I missed your syntax error (btw post any errors immediately next time).
Since awardLev
is an array, you can only use +
with another array, not with an integer. Just use
$endsum += $awardLev[0]
instead. OR if you are expecting multiple values per awardLev
:
$endsum += array_sum($awardLev);
A usefull fact when you have a lot of known components and you want to create dynamic variables with the name of your post variables is doing some like:
foreach ($_POST as $key => $value){
$$key = $value;
}
For example, if you have an item like
<textarea name="postText"></textarea>
You will have a variable called "postText"
Have you tried this..??
$endsum = $endsum.$awardLev;