zedu zedu - 2 months ago 16
PHP Question

How to convert a string variable into int and add the two integers at the same time?

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;

Answer Source

If $_POST["qty_input"] is not valid number, casting to int will return 0.

$_SESSION['cart_qty'] = (int)$_SESSION['cart_qty'] + $intqty;