how to unset the item in $_SESSION array - php

i have 2 functions. First one is adding item to cart, second should delete specific item based on product id.
function AddToCart($pid) {
if (isset($_SESSION['products']['prod_count'])) {
$_SESSION['products']['prod_count'] ++;
$incart = $_SESSION['products']['prod_count'];
$_SESSION['products'][$incart]['product_id'] = $pid;
} else {
$_SESSION['products']['prod_count'] = 0;
$incart = $_SESSION['products']['prod_count'];
$_SESSION['products'][$incart]['product_id'] = $pid;
}
}
function DeleteProduct($pid) {
foreach ($_SESSION['products'] as $key => $my_value) {
foreach ($my_value as $key => $product_id) {
if ($product_id == $pid) {
// do not know how to unset this product
}
}
}
}
I need some idea on how to unset the product if $product_id == $pid or may be some other ideas how to achieve that.
My array look something like:
array(1) { ["products"]=> &array(4)
{ ["prod_count"]=> int(2)
[0]=> array(1) { ["product_id"]=> int(4)}
[1]=> array(1) { ["product_id"]=> int(10) }
[2]=> array(1) { ["product_id"]=> int(11) } } }

The following code would simply solve your problem:
function DeleteProduct($pid) {
foreach ($_SESSION['products'] as $key => $product) {
if ($pid === $product['product_id']) {
unset($_SESSION['products'][$key]);
}
}
}
But to make your work alot easier in the future you could also build your array like this:
$_SESSION['products'] = array(
'product_id' => 'amount',
);
To add a product you would simply do:
$_SESSION['products'][$product_id] += $amount;
To count your products you could use:
count($_SESSION['products']);
Here is a simple example of what your functions could be like:
function addProduct($pid, $value = 1) {
$_SESSION['products'][$pid] += $value;
}
function removeProduct($pid) {
unset($_SESSION['products'][$pid]);
}
function countProducts() {
return count($_SESSION['products']);
}
Good luck!

Related

add more 1 in quantity if item is already in array

I have an array in session.
array(2) {
[0]=> array(5) {
["id"]=> string(1) "3"
["titulo"]=> string(25) "product 1"
["quantidade"]=> int(1)
["preco"]=> string(7) "1000.00"
["image"]=> string(15) "/img/no_img.png"
}
[1]=> array(5) {
["id"]=> string(1) "1"
["titulo"]=> string(43) "product 2"
["quantidade"]=> int(1)
["preco"]=> string(6) "157.20"
["image"]=> string(14) "produtos/1.jpg"
}
}
for example, if user add the same product again (eg: id 3), I'd like to add +1 in its quantity (quantidade) only.
I tried this, but products are always creating a new array, not updating the quantity.
Any ideas why?
if(!empty($_SESSION["cart_item"])) {
if(in_array($produto, array_keys($_SESSION["cart_item"]))) {
foreach($_SESSION["cart_item"] as $k => $v) {
if($produto == $k) {
if(empty($_SESSION["cart_item"][$k]["quantidade"])) {
$_SESSION["cart_item"][$k]["quantidade"] = 1;
}
$_SESSION["cart_item"][$k]["quantidade"] += 1;
}
}
}
else {
$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
}
}
else {
$_SESSION["cart_item"] = $itemArray;
}
$produto is the ID I'd like to update.
The $k variable contains the current array index [0,1,2,3], not the value of the current array id.
I'd try to compare your $producto with $_SESSION["cart_item"][$k]['id'] instead. I've also changed your condition to strictly compare both values ( === ) which is always a good idea.
One more things.
I'm not sure this line is relevent
if(in_array($produto, array_keys($_SESSION["cart_item"]))) {
You are trying to check if $produto is in the keys of $_SESSION["cart_item"]. However, the keys of $_SESSION["cart_item"] are the index that starts at 0. So the id 1 might not be at position 1.
You'd be better of using another variable ( lets say $dirty) to check if your current array was updated.
if(!empty($_SESSION["cart_item"])) {
$dirty = false;
foreach($_SESSION["cart_item"] as $k => $v) {
if($produto === $_SESSION["cart_item"][$k]['id']) {
$dirty = true
if(empty($_SESSION["cart_item"][$k]["quantidade"])) {
$_SESSION["cart_item"][$k]["quantidade"] = 1;
}
$_SESSION["cart_item"][$k]["quantidade"] += 1;
}
}
if(!$dirty) {
// the id was not present in the array
// we need to add it.
$_SESSION["cart_item"][] = [...];
}
}
else {
$_SESSION["cart_item"] = $itemArray;
}
Please note that this code is untested.

PHP arrray and string

I have problems with arrays. When I try to get the first array [0] it does not give me anything.
This is output
array(4) { [0]=> string(0) "" [333]=> string(123) "https://s3-us-west-2.amazonaws.com/hl-cdn-prod60/f/de/d6/fded6f1587f863a9e8fc1c2173143a8782fa655e/700Wx700H-105395-0416.jpg" [334]=> string(125) "https://s3-us-west-2.amazonaws.com/hl-cdn-prod60/e/b9/54/eb954216442547d2ed2c71adbcf73d4f2b3ef903/700Wx700H-105395-a-0416.jpg" [335]=> string(125) "https://s3-us-west-2.amazonaws.com/hl-cdn-prod60/7/16/95/71695917dd17d29648c8f4907000e3c6cab64581/700Wx700H-105395-b-0416.jpg" }
and this is code
private function getImages($dom) {
$images = [];
foreach ($dom->getElementsByTagName('ul') as $ul) {
if ($ul->getAttribute('class') == 'image-thumbnails') {
foreach ($dom->getElementsByTagName('li') as $li) {
$images[] = $li->getAttribute('data-zoom-url');
}
}
}
$images = array_unique($images);
return $images;
}
If you want to exclude empty values, check if the attribute is empty before adding it to the array:
if(!empty($li->getAttribute('data-zoom-url'))) {
$images[] = $li->getAttribute('data-zoom-url');
}

Delete some data from Array in php

I want to delete some data from an array in PHP. Here is the array:
array(4) {
[0]=> array(1) { ["image"]=> string(20) "w85YrKChBGTZ9fQS.jpg" }
[1]=> array(1) { ["image"]=> string(20) "3buahEs6rRWFdYez.jpg" }
[2]=> array(1) { ["image"]=> string(20) "gYPtDrx3sFzkVENB.jpg" }
[3]=> array(1) { ["image"]=> string(20) "JE3rodDvs6521cFm.jpg" }
}
Here is my method and where I am deleting:
public function deleteImage(){
foreach (getCarImages() as $array){
//var_dump($array).'<br>';
$index = array_search('w85YrKChBGTZ9fQS.jpg',$array);
if($index !== FALSE){
var_dump($index).'<br>';
unset($array[$index]);
}else{
echo '<br>else here';
}
}
}
And here is the result of deleteImage()
string(5) "image"
else
here
else
here
else
here
I am confused. How can I delete a nested array from the main array.
If you need to delete a whole subarray from array, then use array_flter function:
public function deleteImage(){
return array_filter(getCarImages(), function ($v) {
return $v['image'] != 'w85YrKChBGTZ9fQS.jpg';
});
}
Update: Anonymous function doesn't know about $imageName variable. You have to use it:
public function deleteImage($imageName = null)
{
$myarray = array_filter(
getCarImages(),
function ($v) use ($imageName) { return $v['image'] != $imageName; }
);
}
You can trans the images as a reference to the function.
public function deleteImage(&$images){
foreach ($images as $k => $array){
//var_dump($array).'<br>';
$index = array_search('w85YrKChBGTZ9fQS.jpg',$array);
if($index !== FALSE){
var_dump($index).'<br>';
unset($images[$k]);
}else{
echo '<br>else here';
}
}
}

Replace values in two dimensional associative array

$update is a two dimensional associative array. Part of the var_dump is:
array(101) {
[0]=> array(27) { ["code"]=> string(4) "2014" ["na1"]=> string(4) "6010" and many more fields following }
[1]=> array(27) { ["code"]=> string(4) "2015" ["na1"]=> string(4) "6010" and many more fields following }
and many more subarrays following of course . . .
Need to replace the code value with a name and created:
foreach($update as $key=>$subarray){;
foreach ($subarray as $subkey=>$val) {
echo $subkey.$val."<br>";//Just for checking
if ($subkey=='code' && $val==2014)
{
$val="Name1";
}
elseif ($key=='code' && $val==2015)
{
$val="Name2";
}
}
}
var_dump($update);
The echo $subkey and $val give perfectly the correct values, however de If statement seems never to be true (or is cancelled out again somehow) as the var_dump is leading again to the original values
Some Stackoverflow research even showed constructions with only one foreach loop, much more elegant, but seems not to reach the second array level.
Is there a better approach? Solution to fix this one?
You are not updating the source array.
foreach($update as $key=>$subarray){
foreach ($subarray as $subkey=>$val) {
echo $subkey.$val."<br>";//Just for checking
if ($subkey=='code' && $val==2014)
{
//$val="Name1";
$update[$key][$subkey] = "Name1" ;
}
elseif ($key=='code' && $val==2015)
{
//$val="Name2";
$update[$key][$subkey] = "Name2" ;
}
}
}
You can access to the field you want by index.
Example :
$i = 0;
$j = 0;
foreach($update as $key=>$subarray){;
foreach ($subarray as $subkey=>$val) {
echo $subkey.$val."<br>";//Just for checking
if ($subkey=='code' && $val==2014)
{
$update[$i][$j] = "Name1";
}
elseif ($key=='code' && $val==2015)
{
$update[$i][$j] = "Name2";
}
$j++
}
$j = 0;
$i++;
}
var_dump($update);
$newArr = array();
foreach($update as $key=>$subarray){
$subNewArr = array();
foreach ($subarray as $item) {
if ($item['code']==2014)
{
$item['code']="Name1";
}
elseif ($item['code']==2015)
{
$item['code']="Name2";
}
array_push($subNewArr, $item);
}
array_push($newArr, $subNewArr);
}
var_dump($update);
Less if else checking

PHP array argument by value, gets modified when looping the array items by reference

I have been having issues with an array being modified when passed by value to a function.
I have inspected the code and inside the function the array is looped getting the elements by reference.
I was surprised to see that after the loop the array items are marked as referenced. I don't know what this means, but must be the origin of my problem.
Let me put an example to see the point.
<?php
error_reporting(E_ALL);
ini_set('display_errors' , 1);
$a = array( array(0) );
echo '--1--';var_dump($a);
dummy($a);
echo '--4--';var_dump($a);
function dummy($arg) {
foreach($arg as &$item) {
$item[0] = 3;
}
dummy2($arg);
echo '--3--';var_dump($arg);
}
function dummy2($arg) {
foreach($arg as &$item) {
$item[1]=9;
}
echo '--2--';var_dump($arg);
}
?>
After this code I would expect that in point 3, $arg would have only one element, but it has two, so it has been modified by dummy2 function.
The output is as follows:
--1--array(1) { [0]=> array(1) { [0]=> int(0) } }
--2--array(1) { [0]=> &array(2) { [0]=> int(3) [1]=> int(9) } }
--3--array(1) { [0]=> &array(2) { [0]=> int(3) [1]=> int(9) } }
--4--array(1) { [0]=> array(1) { [0]=> int(0) } }
Why are the arrays marked as &array after being looped by reference?
How can this be avoid?
You need to unset the loop variable that captures by reference:
<?php
error_reporting(E_ALL);
ini_set('display_errors' , 1);
$a = array( array(0) );
echo '--1--';var_dump($a);
dummy($a);
echo '--4--';var_dump($a);
function dummy($arg) {
foreach($arg as &$item) {
$item[0] = 3;
}
unset($item);
dummy2($arg);
echo '--3--';var_dump($arg);
}
function dummy2($arg) {
foreach($arg as &$item) {
$item[1]=9;
}
unset($item);
echo '--2--';var_dump($arg);
}
?>
See in the documentation for foreach, there is a big red warning that says:
Reference of a $value and the last array element remain even after the
foreach loop. It is recommended to destroy it by unset().
Use key => value pairs and return the array in your functions
<?php
error_reporting(E_ALL);
ini_set('display_errors' , 1);
$a = array( array(0) );
echo '--1--';var_dump($a);
$a = dummy($a);
echo '--4--';var_dump($a);
function dummy($arg) {
foreach($arg as $key => $value) {
$arg[$key][0] = 3;
}
return dummy2($arg);
}
function dummy2($arg) {
foreach($arg as $key => $value) {
$arg[$key][1]=9;
}
return $arg;
}
?>
http://codepad.org/f30c6FUj

Categories