This is my code:
<?php
//for reference
$intqty = (int) $_POST["qty_input"];
(int)$_SESSION['cart_qty'] += $intqty;
?>
The $_POST['qty']
is a string and I'm trying to add and store the values in a session variable and its not working. The output of when I echo $_SESSION['cart_qty'];
is 0;
If $_POST["qty_input"]
is not valid number, casting to int
will return 0
.
$_SESSION['cart_qty'] = (int)$_SESSION['cart_qty'] + $intqty;
If both your variables are valid numbers, the cast will be implicit if you use them as numbers, for example if you try to add them :
$_SESSION['cart_qty'] += $_POST['qty_input'];
No more, no less.
If this line doesn't work, then it's weird. It could mean that one or both of the values is/are not valid number(s) but I assume you already checked the content of your variables.
You would need explicitly show the values stored in your $_POST
and $_SESSION
with something like a var_dump
to be sure the value is indeed a string that could be converted to an int (ie "23"), but even so you should not need to cast the string to an int. PHP supports type juggling which basically implicitly casts variables to the correct type when performing operations on them.
That should explain how to cast a string to an int, as for how to add two integers at the same time, just use +
or +=
depending on where you want the value stored.