Jump to content

$_SESSION['variables'] and array_key_exists


scottybwoy

Recommended Posts

Sorry, thought it was a simple question ;)

			//If product already exists, update the row.
			if (array_key_exists($modelId, $_SESSION['item_buy'])) {
				$price = number_format($price, 2, '.', '');
				$session_qty = $_SESSION['item_buy'][$modelId][1] + $qty;
				$prod_net = number_format($qty * $price, 2, '.', '');
				$prod_vat = number_format($prod_net * VAT, 2, '.', '');
				$prod_gross = number_format($prod_net + $prod_vat, 2, '.', '');

				$_SESSION['item_buy'][$modelId] = array($price, $session_qty, $prod_net, $prod_vat, $prod_gross);
			} else {
				$_SESSION['item_buy'][$modelId] = array($price, $qty, $prod_net, $prod_vat, $prod_gross);
			}

The notice is that the second argument must be an array, but it is not possible for $_SESSION['item_buy'] to be anything but an array.  If I print_r it, it also shows as an array.

 

[edit] I am not that bothered, but just wanted to know if I was using it correctly.

The posted code works for me when $_SESSION['item_buy'] exists and is an array for both a true and false array_key_exists() result.

 

At the time your code is being executed, $_SESSION['item_buy'] either does not exist at all or is not an array. At what point are you doing the print_r()?

 

If $_SESSION['item_buy'] does not exist, you get a notice message about the item_buy index and a warning message about the second argument should be either an array or an object in ... What is the exact error message?

 

 

Ok, no you are correct.  This function is also used to determine whether $_SESSION['item_buy'] exists.  So it would be better to use :

			//If product already exists, update the row.
			if (isset($_SESSION['item_buy']) && array_key_exists($modelId, $_SESSION['item_buy'])) {
				$price = number_format($price, 2, '.', '');
				$session_qty = $_SESSION['item_buy'][$modelId][1] + $qty;
				$prod_net = number_format($qty * $price, 2, '.', '');
				$prod_vat = number_format($prod_net * VAT, 2, '.', '');
				$prod_gross = number_format($prod_net + $prod_vat, 2, '.', '');

				$_SESSION['item_buy'][$modelId] = array($price, $session_qty, $prod_net, $prod_vat, $prod_gross);
			} else {
				$_SESSION['item_buy'][$modelId] = array($price, $qty, $prod_net, $prod_vat, $prod_gross);
			}

 

Correct?  Is there a better way to write this function?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.