how to remove a particular key => value from a session array? - php

let's say i have $_SESSION['cart']; when I print this
echo "<pre>",print_r($_SESSION['cart']),"</pre>";
it will show something like
Array
(
[1] => 2
[2] => 2
)
where the keys are the product IDs and the value is the quantity of each product.
so, if I would want to delete product no. 2 from that session array,
how am to do that ?
I tried the fastest function that came to my mind
public function removeItem($id2){
foreach($_SESSION['cart'] as $id => $qty) {
if ($id == $id2){
unset($_SESSION['cart'][$id]);
}
}
}
it deleted the whole $_SESSION['cart'] data :(

unset($_SESSION['cart'][$id2]);
You don't need to walk through whole array in foreach for this. Simple is better than complicated :)

Why are you looping through? If you get the id you want do delete as a parameter anyway, you can do this:
public function removeItem($id2) {
unset($_SESSION['cart'][$id2]);
}

If you want to clear the id just do :
$_SESSION['cart'][$id] = null;
Hope this help

just do
public function removeItem($id){
unset($_SESSION['cart'][$id]);
}

Related

Array push shopping cart in PHP

I've just started a PHP course. I was asked to create a shopping cart function using array_push. I don't fully understand the code, can anyone help?
I've created an array called $cart
$cart = [
'user' => 'sholmes',
'items' => [$camera, $lens]
We were then asked to create a function called create item, to put items into the shopping cart. The answer is below:
function create_item(&$cart, $item) {
array_push($cart['items'], $item);
return count($cart) - 1;
}
What I don't understand is the last line of code. Why is the return count $cart -1? I thought the point of array_push was to add items to the cart? Our teacher talked through the solution but I don't quite understand it. Any help welcome!
Thanks
Vicki
The function create_item(&$cart, $item) in your case along with adding a new item to the $cart returns the position of the last added item.But array_push function already returns the new number of elements in the array.The function could be simplified to the following:
function create_item(&$cart, $item) {
return array_push($cart['items'], $item) - 1;
}
http://php.net/manual/en/function.array-push.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.

Multiple Keys to an array in if/else search

My code is pretty basic. I'm using an array to generate a datasheet for a product based on it's SKU and a filepath.
My array looks like this:
$a=array(
"/images/ManualSheets/factSheetCLASSIC.pdf"=>"KE800/6",
"/images/ManualSheets/factSheetMICRO.pdf"=>"KE800/12",
"/images/ManualSheets/factSheetSMALL.pdf"=>"KE4000/12",
"/images/ManualSheets/factSheetMEDIUM.pdf"=>"KE8000/12",
);
Where the first Key is the filepath, and the second Key is the SKU (as generated by the system) I then use an if/else to generate a button - so if a product is not in the array it returns a blank value and doesn't have a button which leads to nowhere
$factsheetweblink_url = array_search($product_sku,$a);
if ($factsheetweblink_url==false) {
echo " ";
}
else {
echo "<div class='productpagestockistBTN'>
<img src='/images/FactSheet_btn.png' >
</div>";
}
?>
This code works fine. The catch comes when I have products with different SKUs but the same datasheet file, (same brand and make but a different model). Currently I can only get it to work by uploading multiple copies of the datasheets with different names, but it's becoming a big waste of space.
I have tried using an array as a key to hold multiple values to the one key..
"/images/ManualSheets/factSheetMEDIUM.pdf"=> array("KE8000/12","KE7000/12"),
but it doesn't seem to be working... I'm not quite sure if I need to refine my if statement to search within the sub arrays as well or..?
Any help would be appreciated, thanks in advance.
You should use arrays like this:
$products = array(
0 => array(
"pdf" => "/images/ManualSheets/factSheetCLASSIC.pdf",
"skus" => array("KE800/6","KE900/6")
),
1 => array(
"pdf" => "/images/ManualSheets/factSheetCLASSIC3.pdf",
"skus" => array("KE100/6","KE200/6"))
);
This is because array_search returns just first row whit that key.
Then just do your own search function like:
function findBySku($items, $sku) {
$pdf = ""; // return empty if not found.
foreach($items as $row) {
if (in_array($sku, $row['skus'])) {
$pdf = $row['pdf'];
break;
}
}
return $pdf;
}
and call that function:
$pdf = findBySku($products, "some sku");

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]++;

check is Array empty or not (php)

I am using Cakephp and try to customize the paginator result with some checkboxes .I was pass parameters in URL like this
"http://localhost/myproject2/browses/index/page:2/b.sonic:1/b.hayate:7/b.nouvo:2/b.others:-1/b.all:-2"
and cakephp translate URL to be the array like this
Array
(
[page] => 2
[b.sonic] => 1
[b.hayate] => 7
[b.nouvo] => 2
[b.others] => -1
[b.all] => -2
)
other time when I pass params without checking any checkbox.
"http://localhost/myproject2/browses/index/page:2"
and cakephp translate URL to be the array like this
Array
(
[page] => 2
)
how to simple check if [b.????] is available or not? I can't use !empty() function because array[page] is getting on the way.
If you want to check if a specific item is present, you can use either :
isset()
or array_key_exists()
But if you want to check if there is at least one item which has a key that starts with b. you will not have much choice : you'll have to loop over the array, testing each key.
A possible solution could look like this :
$array = array(
'page' => 'plop',
'b.test' => 150,
'b.glop' => 'huhu',
);
$found_item_b = false;
foreach (array_keys($array) as $key) {
if (strpos($key, 'b.') === 0) {
$found_item_b = true;
break;
}
}
if ($found_item_b) {
echo "there is at least one b.";
}
Another (possibly more fun, but not necessarily more efficient ^^ ) way would be to get the array of items which have a key that starts with b. and use count() on that array :
$array_b = array_filter(array_keys($array), function ($key) {
if (strpos($key, 'b.') === 0) {
return true;
}
return false;
});
echo count($array_b);
If page is always going to be there, you could simply do a count.
if (count($params) == 1) {
echo "There's stuff other than page!";
}
You could be more specific and check page is there and the count is one.
I think this is what you are looking for, the isset function so you would use it like...
if(isset(Array[b.sonic]))
{
//Code here
}

Categories