Search code examples
phpsessionproductcart

PHP foreach array check if stock greater than


Trying to check if stock greater than. When the all of different items is greater than 10 stock I would like to display some text "The requested qty is not available" instead of form submit. Is this possible?

The problem is i have 15 qty from one items in the cart using SESSION. The total of stock is 10 if the qty 15 from one items is greater than stock 10, then shows “the requested qty is not available” so don’t form submit. But i change a value 10 qty from one items less than equal 10 stock. Shows “Your order has been placed.”

$array = array('0' => array('qty' => 15), '1' => array('qty' => 5), '2' => array('qty' => 1));
foreach ($array as $key => $item) {
    if ($item['qty'] !== 0) {
        if ($item['qty'] <= 10) {
            $it = 'Your order has been successfully processed';
        } else {
            $it = 'The requested qty is not available';
        }
    } else {
        $it = 'Some of products are out of stock';
    }
}
echo $it;

For example (1)

One items qty 10

Two items qty 5

Third items qty 1

= if possible form submit (qty less than equal stock 10), then shows “your order has been placed”.

For example (2)

One items qty 15

Two items qty 5

Third items qty 1

= if don’t form submit (qty greater than stock) , then shows “the requested qty is not available.

For example (3)

One items qty 9

Two items qty 4

Third items qty 0

= if don’t form submit, then shows “some of products are out of stock”.


Solution

  • foreach ($array as $key => $item) {
        if($item['qty'] !== 0) {
            if($item['qty'] <= 10)
            {
                $it   =   'Your order has been successfully processed';
            }
            else
            {
                $it   =   'The requested qty is not available';
                break;
            }
        }
        else
        {
            $it   =   'Some of products are out of stock';
            break;
        }
    
    }
    echo $it;
    

    You can simply use a break; to stop your foreach, if a problem in the order appears.

    Just as a idea: You could also use a boolean, if everything fine then process Order, if not give the certain error message. Depends on your next steps.