I Need to add items to array, not replace them - php

I have a little script system. It replaces the array but I need it to add to the array. This is what I have:
$_SESSION['cart']=array(); // Declaring session array
array_push($_SESSION['cart'],'item1'); // Item added to cart
If after this I submit:
$_SESSION['cart']=array(); // Declaring session array
array_push($_SESSION['cart'],'item2'); // Item added to cart
It will contain item2 in array not item1 and item2.
How can I get it to do this?
So I changed up my code a bit and not when I push for example the code below twice it will overwrite the item. How can I make it add another one instead?
array_push($_SESSION['cart']['itemName'] = 13.99);

It seems that you are recreating the array on the second set of code meaning that you will delete everything already in the array. Did you try just array_push without the $_SESSION['cart']=array(); for the second set of code? If not try getting rid of that first line and see if it works.

Use this syntax to append:
$_SESSION['cart'][] = 'item1';
$_SESSION['cart'][] = 'item2';
Edit:
// declare only if needed
if (!array_key_exists('cart', $_SESSION)) $_SESSION['cart'] = array();
// when adding an item at any future time once $_SESSION['cart'] exists:
$_SESSION['cart'][] = array(
'itemName' => 'my item',
'price' => 13.99
);

By calling this line every time :
$_SESSION['cart']=array();
You are cleaning out your cart session. If you wrap that in an if statement as well to check whether the array has already been instantiated, then you won't clean it out each time and you should be able to add to it as expected:
if (!isset($_SESSION['cart'])) {
$_SESSION['cart']=array();
}

You are emptying your array before you add to it you declare $_SESSION['cart'] to equal a new empty array

U declared 2 times $_SESSION['cart']. Remove second declare and you should be good to go.
EDIT :
U don't use correct syntax for array_push.
PHP.net : array_push()
If i understood correctly - the index of key (numeric since array_push) bothers you.
U can bypass by using this code :
$_SESSION['cart'] = array();
$_SESSION['cart']['itemName'] = 12.50;
$_SESSION['cart'] = $_SESSION['cart'] + array("blabla" => 13.99);
print "<pre>";
print_r($_SESSION);
print "</pre>";
Result :
Array
(
[cart] => Array
(
[itemName] => 12.5
[blabla] => 13.99
)
)
LAST EDIT : (!?!)
function set_item_price($itemName, $itemPrice)
{
if(!isset($_SESSION['cart'][$itemName]['itemPrice']))
$_SESSION['cart'][$itemName]['itemPrice'] = $itemPrice;
else
echo "Item Already exists \n <br>";
}
function add_to_cart($itemName, $quantity)
{
if(!isset($_SESSION['cart'][$itemName]['quantity']))
$_SESSION['cart'][$itemName]['quantity'] = $quantity;
else
$_SESSION['cart'][$itemName]['quantity'] += $quantity;
}
// Adding item1 - price 12.50
set_item_price("item1", 12.50);
// Adding item1 - quantity - 2 & 3
// OutPut will be 5
add_to_cart("item1", 2);
add_to_cart("item1", 3);
// Adding item3 - price 15.70
set_item_price("item3", 15.70);
// Adding item1 - quantity - 5
add_to_cart("item3", 5);
print "<pre>";
print_r($_SESSION);
print "</pre>";
?>
RESULT :
Array
(
[cart] => Array
(
[item1] => Array
(
[itemPrice] => 12.5
[quantity] => 5
)
[item3] => Array
(
[itemPrice] => 15.7
[quantity] => 5
)
)
)
Otherwise check on this thread :
Stackoverflow : how-to-push-both-value-and-key-into-array-php

Related

Unset the values behind a key and that key in an associative array

I'd like to say I already took at this and this answer.
Problem:
I have a session variable called "cart" which looks like this.
array (
'cart' =>
array (
2 =>
array (
0 => '2',
1 => 2,
),
),
)
Inside of cart I want to remove the values behind the key 2 so [0 => 2, 1 => 1]. I also want 2 to begone. So it's just a blank array. cart => []. To acomplish this I have this line.
unset($_SESSION["cart"][$id]);
$id is from a get request. I'll show the code for it if that is needed for clarification. However, the result of the above snippet gives me this instead.
array (
3 =>
array (
0 => NULL,
1 => 1,
),
)
Not only does 2 increment to 3, NULL also appears for some reason.
$_SESSION["cart"] is made here in cart.inc.php
<?php
session_start();
// A cart is structured like this
// cart = [item_id: [item_id, amount], item_id: [item_id, amount]]
// item_id is the key to another array that contains the item_id, again and the amount of that item.
if (isset($_GET["remove"])) {
$id = $_GET["remove"];
// Instead of removing the key "id" and all of the values behind it.
// It only changes item_id into NULL.
unset($_SESSION["cart"][$id]);
}
$id = $_GET["id"];
if (isset($_SESSION["cart"])) {
// If the item already exists in the cart modify the existing
// item values instead of creating a new one.
if (isset($_SESSION["cart"][$id])) {
// If the user has changed the amount then this will run.
// Instead of adding by 1 it changes the amount of whatever
// the new amount is.
if (isset($_GET["amt"])) {
$amt = intval($_GET["amt"]);
$_SESSION["cart"][$id][1] = $amt;
} else {
// to increase the item quantity. So + 1 here.
$_SESSION["cart"][$id][1] = $_SESSION["cart"][$id][1] + 1;
}
} else {
// This is if the cart exists, but that item is one that isn't in the cart.
array_push($_SESSION["cart"], [$id, 1]);
}
} else {
// When the cart doesn't exist, set the new cart session variable.
$_SESSION["cart"] = [$id => [$id, 1]];
}
header("location: ../../index.php");
there are multiple problems, so it is easier to past fixed version here neither in comments:
<?php
session_start();
if (!isset($_SESSION["cart"])) $_SESSION["cart"] = []; // initialize card if needed
if (isset($_GET["remove"])) {
$id = intval($_GET["remove"]);
if (isset($_SESSION["cart"][$id])) unset($_SESSION["cart"][$id]);
}
else { // you want this part to be executed only when you add, not when you remove
$id = isset($_GET["id"]) ? intval($_GET["id"]) : 0; // check that id is actually passed and covert it immediately
if ($id > 0) {
$prev_amt = isset($_SESSION["cart"][$id]) ? $_SESSION["cart"][$id][1] : 0; // initialize previous amount
$amt = isset($_GET["amt"]) ? intval($_GET["amt"]) : ($prev_amt + 1); // intialize amount
if ($amt > 0) $_SESSION["cart"][$id] = [$id, $amt];
}
}
header("location: ../../index.php");

Change global 2d array from a function PHP?

$q = $_POST['q'];
$inCart = isset($_COOKIE['cart']) ? unserialize($_COOKIE['cart']) : array();
function alreadyInCart() {
global $inCart, $good, $q;
foreach ($inCart as $inCart1) {
if ($inCart1[0] == $good->id) { // if this good already in cart
$inCart1[1] = $inCart1[1] + $q; // write sum of q's to existing array
return true; // and return true
}
}
return false; // return false if not
}
if (alreadyInCart() == false) { // if good added to cart for the first time
$inCart[] = array($good->id, $q); // add array at the end of array
}
Hello. So my problem is that I'm running a function to find out if $good->id is already inside of 2d $inCart array.
$inCart looks something like this:
Array
(
[0] => Array
(
[0] => 6
[1] => 1
)
[1] => Array
(
[0] => 5
[1] => 1
)
)
Where [0] is a good ID and [1] is an amount of this good in a cart.
So I tracked that function actually does what I want and returns true/false as expected, but looks like it only does it inside of itself. Cause if I put print_r($inCart1[1]) inside of a function it does add up and outputs the sum, as expected. But when I output the array at the end of the code (outside the function) the amount doesn't add up, just stays how it was before the function run.
Any ideas why that happens?
Ok, in case someone faces the same problem: found a solution.
Or should I say found a mistake?
The problem was with the foreach ($inCart as $inCart1). Must be replaced with foreach ($inCart as &$inCart1) in order to change array values in a loop. The other way, it just reads values, bit can't change them.

PHP - How to find the Auto Increment Array id to unset

I am using a form to create several arrays in a Session. Each time the form is submitted a new $_SESSION['item'][] is made containing each new array. The code for this:
$newitem = array (
'id' => $row_getshoppingcart['id'] ,
'icon' => $row_getimages['icon'],
'title' => $row_getimages['title'],
'medium' => $row_getshoppingcart['medium'],
'size' => $row_getshoppingcart['size'],
'price' => $row_getshoppingcart['price'],
'shipping' => $row_getshoppingcart['shipping']);
$_SESSION['item'][] = $newitem;
There could be any number of item arrays based on how many times the user submits the form. Any ideas how can I get the value of the array key that is being put in place of the [] in the session variable? I am trying to create a remove from cart option and cannot figure out how to reference that particular array in the session to unset it.
I am currently displaying the items as such:
<?php foreach ( $_SESSION['item'] AS $item )
echo $item['title'];
echo $item['icon'];
and so on...
Thank you in advance for your time. I really appreciate it.
foreach($_SESSION['item'] as $key => $value) will enable you to seperate the key and value, and ofcourse, to access the value current key has.
To extend this with an example, consider following code:
<?php
$exArray = array("foo"=>"bar", "foo2"=>"bar2);
foreach($exArray as $arrKey => $arrValue):
echo "The key ".$arrKey." has the value of ".$arrValue."<br />\n";
endforeach;
?>
will output:
The key foo has the value of bar.
The key foo2 has the value of bar2.
However, in the same way, if the $arrValue variable is known to hold an array, it will keep it's content. To loop through that second array, you will need to loop it through another foreach statement.
Just specify an index name in your foreach
foreach ($_SESSION['item'] as $idx => $item) {
var_dump($item);
var_dump($_SESSION['item'][$idx]);
}
The var_dumps will be the same.
$var = array_keys($arr);
$count = count($var);
$lastKey = $var[$count - 1];
That work for you?

Implementing cart system using Multidimensional Associative php array

I am not getting the concept of two dimensional arrays in PHP. I am trying to implement a cart system in which an array Session variable store productid and the quantity of it.
For every new entry if it exists its quantity should be increased or if it does'nt then a new id should be added.
Here is my initial code.
function cart_increment_ajax($data, $qtt) {
$_SESSION['count']+=$qtt;
set_cart( $data );
echo $_SESSION['count'];
}
function initialise_cart( ) {
$_SESSION['cart'] =array( );
$_SESSION['totalprice'] = 0;
}
function set_cart( $pid ) {
if(!isset($_SESSION['cart'])) {
initialise_cart( );
}
//else if( int $_SESSION['cart'] pid exists increment count ))
else
// ($_SESSION['cart'] add new pid.
}
I am not getting how to implement the commented lines through Multidimensional associative array ?
A small quick n dirty example of a multi-array in a session keeping a cart
<?php
function add_to_cart($product_id,$count)
{
// no need for global $_SESSION is superglobal
// init session variable cart
if (!isset($_SESSION['cart']))
$_SESSION['cart'] = array();
// check if product exists
if (!isset($_SESSION['cart'][$product_id]))
$_SESSION['cart'][$product_id]=$count;
else
$_SESSION['cart'][$product_id]+=$count;
}
// add some foos and a bar
add_to_cart('foo',2);
add_to_cart('foo',1);
add_to_cart('bar',1);
print_r($_SESSION['cart']);
?>
This will produce
Array
(
[foo] => 3
[bar] => 1
)
HTH
Use the product ID as an index in your array, then simply increment it by using ++.
$_SESSION['cart'][$pid]++;

Query regarding associative arrays PHP

I have a question about associative arrays in php.
I have following array in which there are two items named 4 and 2 respectively.
$items = array(4,2);
Now i want to associate each item's quantity to it which can be done as follows:
$items['4']=23;
$items['2']=0;
which means that there are 23, 'item 4s' and no 'item 2'.
But I sometimes don't know in advance what is there in the $items so i want to associate quantity on basis of location. I wanted to do something like associate 23 to whatever is there on the zero location of the item array:
$items['items[0]']=23;
This of course did not work because its not the right way to extract whatever is placed on the zero location of items. Can anyone please tell me how do i do that?
You are confusing in the use of item and items. I imagine you have both an item array and an items array, else things can easily get hairy.
Anyhow, you just refer to it as a variable, not as a string:
$items[$item[0]] = 23;
Let me get this straight. So you start with an array that looks like this:
$items = array( 0 => 4, 1 => 2 )
And you want to end up with an array that looks like this: ?!
$items = array( 0 => 4, 1 => 2, 2 => 0, 4 => 23 )
I think you should use your array as a kind of "map". The item number is your key, and the quantity your value.
By calling
$items = array(4,2);
you create
$items[0] = 4;
$items[1] = 2;
but you want to use the 4 and 2 as a key in your array. So you should instead use
$items = array( 4 => false, 2 => false );
where false stands for an item that has not yet a quantity associated (could also be e.g. -1).
This creates
$items[2] = false;
$items[4] = false;
When using false, you can check for not assigned values by calling
if ($items[4] === false) {
echo "No quantity set!";
}
And now the second step.. if you want to assign the item #4 a quantity of 23, just call
$items[4] = 23;
So I don't think you will want to rely on the order inside your array..

Categories