PHP: SESSION data not being stored - php

This data comes from a POST form, the idea is to simply add more lines whenever a new product is added.
The current output is:
l. Banana 3 units: 150
Please take a look into the script (specially the foreach loop):
<?php
session_start();
//Getting the list
$list= $_SESSION['list'];
//stock
$products = array(
'Pineaple' => 500, 'Banana' => 50, 'Mango' => 150,
'Milk' => 500, 'Coffe' => 1200, 'Butter' => 300,
'Bread' => 450, 'Juice' => 780, 'Peanuts' => 800,
'Yogurt' => 450, 'Beer' => 550, 'Wine' => 2500,
);
//Saving the stuff
$_SESSION['list'] = array(
'item' => ($_POST['product']),
'quantity' => ($_POST['quantity']),
'code' => ($_POST['code']),
);
//price
$price = $products[($_SESSION['list']['item'])] * $_SESSION['list']['quantity'];
$_SESSION['list']['price'] = $price;
//listing
echo "<b>SHOPPIGN LIST</b></br>";
foreach($_SESSION as $key => $item)
{
echo $key[''], '. ', $item['item'], ' ', $item['quantity'], ' units: ', $item['price'];
}
//Recycling list
$_SESSION['list'] = $list;
echo "</br> <a href='index.html'>Return to index</a> </br>";
//Printing session
var_dump($_SESSION);
?>

change this code:
//Saving the stuff
$_SESSION['list'] = array(
'item' => ($_POST['product']),
'quantity' => ($_POST['quantity']),
'code' => ($_POST['code']),
);
to
//Saving the stuff
$_SESSION['list'][] = array(
'item' => ($_POST['product']),
'quantity' => ($_POST['quantity']),
'code' => ($_POST['code']),
);
and remove this code:
//Recycling list
$_SESSION['list'] = $list;
Now, you'll get a new entry in $_SESSION every time you POST to the page.
Also, if you want your output to look like:
l. Banana 3 units: 150
2. Orange 5 units: 250
etc
then you'll need to change the echo in the foreach() loop from
echo $key[''] . // everything else
to just
echo ($key+1) . // everything else
Since key will be your array index starting at 0, you'll need to do a +1 every iteration, otherwise your list would look like
0. Banana 3 units: 150
1. Orange 5 units: 250

As iandouglas wrote, you are overwriting the session variable every time. The following code also fixes some undefined index issues and already existing products.
// Test POST data.
$_POST['product'] = 'Pineaple';
$_POST['quantity'] = 1;
$_POST['code'] = 1;
//Getting the list
$_SESSION['list'] = isset($_SESSION['list']) ? $_SESSION['list'] : array();
//stock
$products = array(
'Pineaple' => 500, 'Banana' => 50, 'Mango' => 150,
'Milk' => 500, 'Coffe' => 1200, 'Butter' => 300,
'Bread' => 450, 'Juice' => 780, 'Peanuts' => 800,
'Yogurt' => 450, 'Beer' => 550, 'Wine' => 2500,
);
//Saving the stuff
$new_item = array(
'item' => $_POST['product'],
'quantity' => $_POST['quantity'],
'code' => $_POST['code'],
'price' => $products[$_POST['product']] * $_POST['quantity'],
);
$new_product = true;
foreach($_SESSION['list'] as $key => $item) {
if ($item['item'] == $new_item['item']) {
$_SESSION['list'][$key]['quantity'] += $new_item['quantity'];
$_SESSION['list'][$key]['price'] = $products[$new_item['item']] * $new_item['quantity'];
$new_product = false;
}
}
if ($new_product) {
$_SESSION['list'][] = $new_item;
}
//listing
echo "<b>SHOPPIGN LIST</b></br>";
foreach($_SESSION['list'] as $key => $item) {
echo 'key '. $key. ' '. $item['item'], ' ', $item['quantity'], ' units: ', $item['price']. '<br />';
}

Related

Looping thru array for sum of one element

I have a shopping cart with three items like this:
$cart = [
1031 => [
'id' => '1031',
'model' => 'tr16',
'price' => 100,
'discount_applied' => '',
'promo_name' => '',
'promo_id' => ''
],
1032 => [
'id' => '1032',
'model' => 'tr16g',
'price' => 100,
'discount_applied' => '',
'promo_name' => '',
'promo_id' => ''
],
1034 => [
'id' => '1034',
'model' => 'tr17g',
'price' => 100,
'discount_applied' => '',
'promo_name' => '',
'promo_id' => ''
]
];
I have an array of IDs representing items eligible for a discount like this:
$itemIds = [
0 => [
0 => 1031
],
1 => [
0 => 1032
]
];
I loop thru each array and change the price where the ID in $cart matches ID in $itemIds by applying a 20% discount, and also add new elements. That code looks like this:
foreach($cart as &$item) {
foreach($itemIds as $ids) {
foreach($ids as $key => $value) {
if ($item['id'] == $value)
{
$item['discount_applied'] = $item['price'] * 0.2;
$item['price'] = $item['price'] * .80;
$item['promo_name'] = 'Test promo';
$item['promo_id'] = 36;
}
}
}
}
Printing the cart to the screen before and after the loop shows it's working as expected.
However, I encounter a problem when trying to loop through the modified $cart and calculate the sum of individual discounts.
My loop looks like this:
$cart['total_discount'] = 0;
foreach($cart as $item)
{
$cart['total_discount'] += $item['discount_applied'];
}
echo 'Total discount:' . $cart['total_discount'];
I expect to see the sum of discounts = 40, but instead = 60. Printing the cart to the screen before and after the loop shows that items 1031 and 1032 have a value of 20 in discount_applied and that item 1034 has no value.
Any help in identifying where I have an error or errors is appreciated.
Here's all the code if you want to copy/paste.
$cart = [
1031 => [
'id' => '1031',
'model' => 'tr16',
'price' => 100,
'discount_applied' => '',
'promo_name' => '',
'promo_id' => ''
],
1032 => [
'id' => '1032',
'model' => 'tr16g',
'price' => 100,
'discount_applied' => '',
'promo_name' => '',
'promo_id' => ''
],
1034 => [
'id' => '1034',
'model' => 'tr17g',
'price' => 100,
'discount_applied' => '',
'promo_name' => '',
'promo_id' => ''
]
];
$itemIds = [
0 => [
0 => 1031
],
1 => [
0 => 1032
]
];
echo '<h2>Cart BEFORE discount</h2>'; echo '<pre>';print_r($cart); echo '</pre>';
foreach($cart as &$item) {
foreach($itemIds as $ids) {
foreach($ids as $key => $value) {
if ($item['id'] == $value)
{
$item['discount_applied'] = $item['price'] * 0.2);
$item['price'] = $item['price'] * .80;
$item['promo_name'] = 'Test promo';
$item['promo_id'] = 36;
}
}
}
}
echo '<h2>Cart AFTER discount</h2>'; echo '<pre>';print_r($cart); echo '</pre>';
$cart['total_discount'] = 0;
foreach($cart as $item)
{
echo $item['discount_applied'] . '<br>';
$cart['total_discount'] += $item['discount_applied'];
}
echo 'Total discount:' . $cart['total_discount'];
Your use of &$item in the initial loop needs to be used in your final loop also. The loop where you adding up the discount total. You will also need to see if the discount value is a number since, in the code you posted, the 3rd item in the cart will have a blank value for the discount which will throw a non-numeric error when trying to add it to the discount total.
Your final loop modified to work:
$cart['total_discount'] = 0;
foreach($cart as &$item) {
echo '*' . $item['discount_applied'] . '*<br />'; // just to show what is or isn't there
$cart['total_discount'] += (is_numeric($item['discount_applied']) ? $item['discount_applied'] : 0);
}
echo 'Total discount:' . $cart['total_discount'];

how to calculate the sum of same array values in PHP

I have an array like this
$estimate[0]=>
'gear' =>'MMG'
'total' => 315
'efforts' => 9
'afh' => 18
$estimate[1]=>
'gear' =>'MMG'
'total' => 400
'efforts' => 2
'afh' => 6
$estimate[2]=>
'gear' =>'BOO'
'total' => 200
'efforts' => 20
'afh' => 16
$estimate[3]=>
'gear' =>'BOB'
'total' => 250
'efforts' => 20
'afh' => 16
I want to calculate the sum of total, efforts and afh in which gear is same and it will be stored in the another array. Following my coding is working when the array (estimate) size is less than 5.
$calculate = array();
for($et=0;$et<count($estimate);):
if($et==0):
$calculate[$et]['gear'] = $estimate[$et]['gear'];
$calculate[$et]['total'] = $estimate[$et]['total'];
$calculate[$et]['efforts'] = $estimate[$et]['efforts'];
$calculate[$et]['afh'] = $estimate[$et]['afh'];
goto loopend;
endif;
for($cet=0;$cet<count($calculate);$cet++):
if($estimate[$et]['gear'] == $calculate[$cet]['gear']):
$calculate[$cet]['total'] = $calculate[$cet]['total'] + $estimate[$et]['total'];
$calculate[$cet]['efforts'] = $calculate[$cet]['efforts'] + $estimate[$et]['efforts'];
$calculate[$cet]['afh'] = $calculate[$cet]['afh'] + $estimate[$et]['afh'];
goto loopend;
endif;
endfor;
$calculate[$et]['gear'] = $estimate[$et]['gear'];
$calculate[$et]['total'] = $estimate[$et]['total'];
$calculate[$et]['efforts'] = $estimate[$et]['efforts'];
$calculate[$et]['afh'] = $estimate[$et]['afh'];
goto loopend;
loopend:$et++;
endfor;
The coding is not working more than many gears. Sometimes it works. I can't find the issues. Please help me to solve the issues.
You might use array_reduce:
$result = array_reduce($estimate, function($carry, $item) {
if (!isset($carry[$item["gear"]])) {
$carry[$item["gear"]] = $item;
return $carry;
}
$carry[$item["gear"]]["total"] += $item["total"];
$carry[$item["gear"]]["efforts"] += $item["efforts"];
$carry[$item["gear"]]["afh"] += $item["afh"];
return $carry;
});
Demo
As per my comment use foreach loop when your array length is not define
Here is your desired code
<?php
$estimate = array(
"0" => array (
"gear" => 35,
"total" => 30,
"efforts" => 39,
"afh" => 39,
),
"1" => array (
"gear" => 35,
"total" => 30,
"efforts" => 39,
"afh" => 39,
),
"2" => array (
"gear" => 35,
"total" => 30,
"efforts" => 39,
"afh" => 39,
),
);
$gear=0;
$total=0;
$efforts=0;
$afh=0;
foreach ($estimate as $key => $value) {
$gear=$gear+$value['gear'];
$total=$gear+$value['total'];
$efforts=$gear+$value['efforts'];
$afh=$gear+$value['afh'];
}
echo "<pre>";
$result = array('gear' => $gear, 'total' => $total,'efforts' => $efforts,'afh' => $afh);
echo "<pre>";
print_r($result);
you can check the result HERE
<?php
$new_arr = array();
$estimate[0] =array(
'gear' =>'MMG',
'total' => 315,
'efforts' => 9,
'afh' => 18
);
$estimate[1]=array(
'gear' =>'MMG',
'total' => 400,
'efforts' => 2,
'afh' => 6,
);
$estimate[2]=array(
'gear' =>'BOO',
'total' => 200,
'efforts' => 20,
'afh' => 16,
);
$estimate[3]=array(
'gear' =>'BOB',
'total' => 250,
'efforts' => 20,
'afh' => 16,
);
foreach ($estimate as $key => $value) {
$new_arr[$value['gear']] = array(
'total' => (isset($new_arr[$value['gear']]['total']) ? ($new_arr[$value['gear']]['total'] + $value['total']) : $value['total'] ),
'efforts' => (isset($new_arr[$value['gear']]['efforts']) ? ($new_arr[$value['gear']]['efforts'] + $value['efforts']) : $value['efforts'] ),
'afh' => (isset($new_arr[$value['gear']]['afh']) ? ($new_arr[$value['gear']]['afh'] + $value['afh']) : $value['afh'] )
);
}
echo "<pre>";print_r($new_arr);

PHP: Remove invalid array value?

I'm using two arrays, one is a POST string (product), and another is a predefined set of values(products).
They work together as:
$products[$_POST['product']]
This is okay if the POST value is exactly one of the following:
$products = array(
'Pineaple' => 500, 'Banana' => 50, 'Mango' => 150,
'Milk' => 500, 'Coffe' => 1200, 'Butter' => 300,
'Bread' => 450, 'Juice' => 780, 'Peanuts' => 800,
'Yogurt' => 450, 'Beer' => 550, 'Wine' => 2500,
);
Otherwise it will pop Undefined Index messages. Since this is a SESSION, I need to somehow keep a list of items, but remove the invalid ones from the array and echo a message.
Please check the screenshot: http://img36.imageshack.us/img36/9121/20110430004019.jpg
This is the script I'm using:
<?php
session_start();
//Getting the list
$_SESSION['list'] = isset($_SESSION['list']) ? $_SESSION['list'] : array();
//stock
$products = array(
'Pineaple' => 500, 'Banana' => 50, 'Mango' => 150,
'Milk' => 500, 'Coffe' => 1200, 'Butter' => 300,
'Bread' => 450, 'Juice' => 780, 'Peanuts' => 800,
'Yogurt' => 450, 'Beer' => 550, 'Wine' => 2500,
);
//Saving the stuff
$new_item = array(
'item' => $_POST['product'],
'quantity' => $_POST['quantity'],
'code' => $_POST['code'],
'price' => $products[$_POST['product']] * $_POST['quantity'],
);
$new_product = true;
foreach($_SESSION['list'] as $key => $item) {
if ($item['item'] == $new_item['item']) {
$_SESSION['list'][$key]['quantity'] += $new_item['quantity'];
$_SESSION['list'][$key]['price'] =
$products[$new_item['item']] * $new_item['quantity'];
$new_product = false;
}
}
if ($new_product) {
$_SESSION['list'][] = $new_item;
}
//listing
echo "<b>SHOPPING LIST</b></br>";
foreach($_SESSION['list'] as $key => $item) {
echo 'Product .'. $key. ' '. $item['item'], ' ',
$item['quantity'], ' units: ', $item['price']. '<br />';
}
echo "</br> <a href='index.html'>Return to index</a> </br>";
//Printing session
var_dump($_SESSION);
//session_destroy();
?>
You should use isset or array_key_exists to check whether the key exists before reading it:
if (isset($products[$_POST['product']])) {
// product in stock
} else {
// product not in stock
}
And if you use the same key for your product list in $_SESSION['list'], you don’t need to iterate the whole list to find the same product in the list:
if (isset($_SESSION['list'][$_POST['product']])) {
// update product in list
$_SESSION['list'][$_POST['product']]['quantity'] += $_POST['quantity'];
$_SESSION['list'][$_POST['product']]['price'] = $products[$_POST['product']] * $_POST['quantity'];
} else {
// add product to list
$_SESSION['list'][$_POST['product']] = array(
'item' => $_POST['product'],
'quantity' => $_POST['quantity'],
'code' => $_POST['code'],
'price' => $products[$_POST['product']] * $_POST['quantity'],
);
}
Note that this will always only add items to the list. You should add some functionality to also update and remove items. And don’t forget to validate the data before using it (e.g. so that people don’t get refund if they enter a negative quantity).
I would imagine you want to use the array_intersect_assoc function. it returns the items that are in both of your arrays.

PHP: Foreach echo not showing correctly

The output should look like this:
1. Yougurt 4 units price 2000 CRC
But I'm currently getting this:
item. Y Y unitsYquantity. 3 3 units3code. S S unitsSprice. units
This is the script:
<?php
session_start();
//Getting the list
$list[]= $_SESSION['list'];
//stock
$products = array(
'Pineaple' => 500, 'Banana' => 50, 'Mango' => 150,
'Milk' => 500, 'Coffe' => 1200, 'Butter' => 300,
'Bread' => 450, 'Juice' => 780, 'Peanuts' => 800,
'Yogurt' => 450, 'Beer' => 550, 'Wine' => 2500,
);
//Saving the stuff
$_SESSION['list'] = array(
'item' => ($_POST['product']),
'quantity' => ($_POST['quantity']),
'code' => ($_POST['code']),
);
//price
$price = $products[($_SESSION['list']['item'])] * $_SESSION['list']['quantity'];
$_SESSION['list']['price'] = $price;
//listing
echo "<b>SHOPPIGN LIST</b></br>";
foreach($_SESSION['list'] as $key => $item)
{
echo $key, '. ', $item['item'], ' ', $item['quantity'], ' units', $item['price'];
}
//Recycling list
$_SESSION['list'] = $list;
echo "</br> <a href='index.html'>Return to index</a> </br>";
//Printing session
print_r($_SESSION);
?>
The problem is that you are nested 1 level deeper in the arrays than you think you are. To make it clear, the $_SESSION may look lik this (just before entering the foreach):
array(1) {
["list"] => array(3) {
["item"] => string(8) "Pineaple"
["quantity"] => int(30)
["price"] => int(15000)
}
}
(you can use var_dump($var) or print_r($var) methods to see the value: http://php.net/manual/en/function.var-dump.php http://php.net/manual/en/function.print-r.php)
When iterating over $_SESSION["list"], you pass the loop 3 times. In the first iteration, $key is "item", $value "Pineaple".
echo $key, '. ', $item['item'], ' ', $item['quantity'], ' units', $item['price'];
"item . P P units <empty>"
Why?
String "item" is obvious, it's just printed out.
$item['item'] -> 'item' is cast to (int)0, so the first character of $item (Pineaple) is printed: P
(The examples of string->int conversion rules are for example here: http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion)
$item['quantity'] -> the same as above
$item['price'] -> since the price is much higher than the length of the string, empty string is printed:
$myvar = "hi";
echo $myvar[12234]; // prints empty string
In every iteration you get this output, just the first word is changing. Put echo "<br />" at the end of the iteration and you will see it.
I hope this helps you a bit.

PHP: Array > Sum all the numeric elements?

I found a reference in the PHP manual, but my interpretation is pretty much wrong:
$total = (sum ( array $_SESSION['list'][$item]['price'] ));
I want to sum the price of all the items in the array SESSION.
Please check the screenshot: http://img684.imageshack.us/img684/6070/20110430010324.jpg
This is the code I'm using:
<?php
session_start();
//Getting the list
$_SESSION['list'] = isset($_SESSION['list']) ? $_SESSION['list'] : array();
//stock
$products = array(
'Pineaple' => 500, 'Banana' => 50, 'Mango' => 150,
'Milk' => 500, 'Coffe' => 1200, 'Butter' => 300,
'Bread' => 450, 'Juice' => 780, 'Peanuts' => 800,
'Yogurt' => 450, 'Beer' => 550, 'Wine' => 2500,
);
//Saving the stuff
$new_item = array(
'item' => $_POST['product'],
'quantity' => $_POST['quantity'],
'code' => $_POST['code'],
'price' => $products[$_POST['product']] * $_POST['quantity'],
);
$new_product = true;
foreach($_SESSION['list'] as $key => $item) {
if ($item['item'] == $new_item['item']) {
$_SESSION['list'][$key]['quantity'] += $new_item['quantity'];
$_SESSION['list'][$key]['price'] = $products[$new_item['item']] * $new_item['quantity'];
$new_product = false;
}
}
if ($new_product) {
$_SESSION['list'][] = $new_item;
}
//listing
echo "<b>SHOPPING LIST</b></br>";
foreach($_SESSION['list'] as $key => $item) {
echo 'Product .'. $key. ' '. $item['item'], ' ', $item['quantity'], ' units: ', $item['price']. '<br />';
}
echo "</br> <a href='index.html'>Return to index</a> </br>";
//Printing session
var_dump($_SESSION);
//session_destroy();
?>
$total = 0;
foreach($_SESSION['list'] as $item) {
$total += $item['price'];
}
Or if you prefer a functional style (PHP 5.3):
$total = array_reduce($_SESSION['list'], function($a, $b) {
return $a['price'] + $b['price'];
});

Categories