Removing array element does not work - php

there is a $_SESSION array that holds the ID of user's currently selected products (which are in the cart). Now, when the user sees his bill, he want to remove an item (product) from his cart, I have put him a link to do so. but the script does not work.
I have configured a $_GET['itemid'] in the URL and by using it, I unset() that array element.
BUT it does not work. What should I do? Here is my code
function remove_from_cart($stack_id) // stack_id is the id of the item in cart array ($_SESSION)
{
for($i=0; $i < count($_SESSION['add-to-cart-item']); $i++)
{
if($_SESSION['add-to-cart-item'][$i] == $stack_id)
{
unset($_SESSION['add-to-cart-item'][$stack_id]);
}
}
}

in your code
if($_SESSION['add-to-cart-item'][$i] == $stack_id)
{
unset($_SESSION['add-to-cart-item'][$stack_id]);
}
you find that $stack_id equals $_SESSION['add-to-cart-item'][$i] and not $i
which means that you need to unset $_SESSION['add-to-cart-item'][$i].
good luck

You should unset with [$i]
unset($_SESSION['add-to-cart-item'][$i]);

Related

PHP check for values before the loop to check

I have a JSON multi-dimensional array of products from Shopify that I am looping through. Each product has 3 options and each option can have infinite numbers of values.
For example:
Lamp (product)
Glass Finish (option)
Clear (value)
Smoke (value)
Metal Finish (option)
Polished Chrome (value)
Drop (option)
600mm (value)
800mm (value)
Within the loop I am creating rows within a 'repeater' field in a CMS (one for each option and then a repeater within each option for each value).
This is all fine BUT I want to do a few checks as the array of products is cached to every 30 minutes so if the cache was updated and either an option was removed or a value to that option was added then it should update.
I have my first check in place (loop through all the existing repeater options that have been added, before doing anything, and if an option already exists then skip it (and thus not creating multiple of the same options).
What I need to do is to check each of the values to see if any new ones have been added. I can write the code to actually add the value to the repeater field but I am unsure how to check as by this point, if the option already exists, it skips over.
Any thoughts?
foreach($product['options'] as $option) {
foreach($p->shop_product_options as $options) {
// If this option already exists... then skip the parent loop on this product
if ($options->global_text == $option['name']) {
continue 2;
}
}
$options = $p->shop_product_options->getNew();
$options->of(false);
$options->global_text = $option['name'];
$options->save();
$p->shop_product_options->add($options);
foreach($option['values'] as $o) {
$values = $options->shop_product_options_option->getNew();
$values->of(false);
$values->global_text = $o;
$values->save();
$options->save();
$options->shop_product_options_option->add($values);
}
$options->save();
}
Still not sure I am completely understanding what you are after but it sounds like you need something like this :
foreach($product['options'] as $option) {
$optionNames = array_column($options, 'name');
$options = $p->shop_product_options->getNew();
foreach($option['values'] as $o) {
$values = $options->shop_product_options_option->getNew();
if($values->global_text === $o && in_array($option->global_text, $optionNames, true)) {
continue 2;
}
$values->of(false);
$values->global_text = $o;
$values->save();
$options->shop_product_options_option->add($values);
}
$options->of(false);
$options->global_text = $option['name'];
$p->shop_product_options->add($options);
$options->save();
}
array_column will create an array getting all the values of a multidimensional array when the key is name, and then the if statement will look for a combination of name and value.
And since the saving logic for the option is below the loop for the values,
it will check the cache before saving anything, this might not be a copy/paste answer, i'm just giving you some logic to work with

how to add to an array and not change it's first value?

hey there so basically i'm trying to make a cart and i want the id products to be in a array so that i can serialize them in a cookie for 15 days, the problem i that each time i press the button "add to cart" it changes the previous id instead of adding to the array, i've tried making a loop and changing the index each time and i've tried just adding with $cart[]=$itemId; and the array_push(); function, nothing seems to work.
if (isset($_POST['item'])) {
$item = $_POST['item'];
$panier = array();
$panier[] = $item;
print_r($panier);
}
Just to explain the code, this code will be used when the add to cart button is pressed and retain the product id from the post variable and then add to the array each time but instead i only get a single value in the array that keeps changing everytime i press the button to add.
That's because you're creating a new array each time and then just adding one value to it. Remove $panier = array() to avoid creating a new array each time.
Combining #IncredibleHat's suggestion into working example:
$item = 0;
while($item <= 5) {
if (!isset($panier)) { $panier = array(); }
$panier[] = $item;
$item++;
}
print_r($panier);
Notice that if you remove the if(!isset($panier), then $panier only ends up containing the last value, because it gets re-initialised to empty every iteration through the loop.
In addition to not using storage that persists between requests, your method prevents people buying more than one of an item:
<?php
session_start();
if (isset($_POST['item'])) {
$_SESSION['panier'][$_POST['item']]=
isset($_SESSION['panier'][$_POST['item']) ?
$_SESSION['panier'][$_POST['item']] + 1 :
1;
}

Store and check multiple $_SESSION

I have 3 objects with same variable but rendered with diferent values.
001 - Title one
002 - Title two
003 - Title three
I need to check on another block of page if this first three are the same. The only thing that comes to mind is store this variables in a $_SESSION. So far so good. The problem is that it only stores last value (obviously).
CODE
/* -- block one --*/
session_start();
$_SESSION['lasttitle'] = $item->getTitle;
echo $item->getTitle(); //rendering 1st object
echo $item->getTitle(); //rendering 2nd object
echo $item->getTitle(); //rendering 3rd object
/* -- block two --*/
session_start();
$last3 = $_SESSION['lasttitle'];
if($item->getTitle() != $last3) {
//don't render last 3
}
$_SESSION['lastTitles'][] = $item->getTitle();
$_SESSION['lastTitles'] = array_slice($_SESSION['lastTitles'], -3);
..
if (in_array($item->getTitle(), $_SESSION['lastTitles'])) ..
This stores an array of the last three titles, and checks whether a title is in this array.
Create multidimensional session:
$_SESSION['lasttitle'][$item->id] = $item->getTitle();
$_SESSION['lasttitle'][$item2->id] = $item2->getTitle();
$_SESSION['lasttitle'][$item3->id] = $item3->getTitle();
And check if that element is in array:
$total = 0;
foreach ($items as $item) {
if (isset($_SESSION['lasttitle'][$item->id])) {
$total++;
}
}
if ($total == 3) {
// Do something, it's all 3 titles in session!
}
I know it may be better solution, but I don't understand full algorithm. Also, to compare some arrays, you can use array_diff_assoc()
I think storing data as array in session might help you. Simply gather all titles you need in an array and put it into $_SESSION (instead of one variable). One the next page you will be able to analyze data you have and choose variables you need.

How to remove a blank array from option input in php

Hi I´m trying to put an array into option input. But the problem is I get one blank option.
I want to remove it.
Here is what I'm trying to do:
<select name "x">
$myarray=array('black','blue','brown');
for ($i=0;$i<=count($myarray);$i++){
if ( $row['colur']==$myarray[$i]) {//if value in database = array$i
echo"<option value='$myarray[$i]' selected>$myarray[$i]</option>";
} else {
echo"<option value='$myarray[$i]'>$myarray[$i]</option>";
}
}
You should loop one item less:
for ($i=0;$i < count($myarray);$i++) {
The last $i your loop "sees" is count($myarray) which is 3 in your case. However, because arrays are zero-indexed, item $myarray[3] doesn't exist (it goes from 0 to 2). The if fails and $myarray[3] is shown, which doesn't exist: you also get an error of level "notice" in your server logs (which should be the trigger to find this all out yourself).
To prevent all this, use foreach:
foreach ($myarray as $color) {
// use $color instead of $myarray[$i]
}
As array index start from 0 to (array length -1), you should mention your for loop accordingly i.e
$array_length = count($myarray);
for ($i=0;$i < $array_length;$i++) {
//your code
}

Removing an item from shopping cart array

I'm building a shopping cart, I save the orders in a multidimensional array which is stored in a session, $_SESSION['cart']
A product is represented by something like
$product_array=array($id,$description,$price);
The multidimensional array is the array of the $product_array.s
The $id's are unique.
The issue is, When i want to remove a product from the multidimensional $_SESSION['cart']
array based on the id, it works if it's just one item in the cart, but if more, it doesn't work, the items seems to be removed but it's 'ghost' is left behind in the cart. The code
is something like this :
//get $id, $count is elements in array
for ($r = 0; $r <= $count-1; $r++)
{
if($_SESSION['cart'][$r][0]=="$id")
{
unset($_SESSION['cart'][$r]);
echo "<div class=success>The item has been removed from your shopping cart.</div>";
break;
}
}
try this one function and that is working for me
function remove_product($id){
$id=intval($id);
$max=count($_SESSION['cart']);
for($i=0;$i<$max;$i++){
if($id==$_SESSION['cart'][$i]['id']){
unset($_SESSION['cart'][$i]);
break;
}
}
$_SESSION['cart']=array_values($_SESSION['cart']);
if($_REQUEST['command']=='delete' && $_REQUEST['id']>0){
remove_product($_REQUEST['id']);
}
else if($_REQUEST['command']=='clear'){
unset($_SESSION['cart']);
}
else if($_REQUEST['command']=='update'){
$max=count($_SESSION['cart']);
for($i=0;$i<$max;$i++){
$id=$_SESSION['cart'][$i]['id'];
$q=intval($_REQUEST['qty'.$id]);
if($q>0 && $q<=999){
$_SESSION['cart'][$i]['qty']=$q;
}
else{
$msg='Some proudcts not updated!, quantity must be a number between 1 and 999';
}
}
}
Check if register_global is on in your php.conf. Try to use following syntax to unset both:
if($_SESSION['cart'][$r][0]=="$id") {
$_SESSION['cart'][$r] = NULL;// this is just to be sure =)
unset($_SESSION['cart'][$r], $cart[$r]);
echo "<div class=success>The item has been removed from your shopping cart.</div>";
break;
}
The following code works, maybe it will help You find what's wrong with Yours:
session_start();
$i=0;
$_SESSION['cart'][]=array($i++,'sds',99);
$_SESSION['cart'][]=array($i++,'sds',100);
$_SESSION['cart'][]=array($i++,'sds',20);
$_SESSION['cart'][]=array($i++,'sds',10);
$id = 2;
$count = count($_SESSION['cart']);
for ($r=0;$r<$count;$r++)
{
echo "num=$r<br>";
if(isset($_SESSION['cart'][$r]) && $_SESSION['cart'][$r][0]==$id)
{
unset($_SESSION['cart'][$r]);
echo "The item has been removed from your shopping cart.<br>";
break;
}
}
session_write_close();
As stated I think the issue has to do with the layout of your array and what you try to check against in your for loop or perhaps some PHP setting. Have you initiated a session for example? I would probably move to use an array of product references. Working with plain arrays can quickly become a nightmare where you accidently reference the wrong object without any kind of warning etc. Encapsulated objects fetched with well formed function names helps avoid this.
Something like
$cart = array($productId => $quantity, $productId2 => $quantityOfSecondProduct);
And then have an array that has all the product info data
$products = array($product1...);
where each product is of the type
class Product
{
$productId;
$productName;
$productDescription;
... etc
}
Then you have all the data separated but easily accessible and you can delete one or more entries in the cart based on the products id easily but just referencing it and deleting if quantity is 0.
if(($cart[$productId] - $quantityToRemove) <= 0)
unset($cart[$productId]);
else
$cart[$productId] -= $quantityToRemove;
Note that filling the products etc should preferably be done from some data source, I would also have put the entire cart as a class with nice functions and a bit more error checking should be in place ;)

Categories