Removing items from a session - php

I'm having trouble removing items in a session array in a shopping cart project. The following code should take the selected item and remove it from the session. However the end result is just the same session as before with nothing removed. I've seen similar problems by googling, but haven't found a working solution yet. Here is the stripped down code:
<?php
session_start();
$removeditem = $_GET['item']; // this identifies the item to be removed
unset($_SESSION['stuff'][$removeditem]); // "stuff" is the existing array in the session
?>
Here are what print_r gives for the following (using "7" as the example of the removed item):
$removeditem:
7
$_SESSION['stuff'] (before and after removal)
Array
(
[0] => 7
[1] => 24
[2] => 36
)
Am I missing something obvious?

You are deleting the item with the KEY being equal to $removedItem. It seems to me from your example that you are trying to delete the element that has the VALUE equal to removedItem. In this case, you need to do a foreach loop to identify the key and then delete it.
foreach($_SESSION['stuff'] as $k => $v) {
if($v == $removeditem)
unset($_SESSION['stuff'][$k]);
}

You need to first get the key of the element and then unset it. Here's the code you should use:
if(($key = array_search($removeditem, $_SESSION['stuff'])) !== FALSE)
unset($_SESSION['stuff'][$key]);

The most simple way is:
<?php
session_start();
$removeditem = $_GET['item'];
$temp = array_flip($_SESSION['stuff']);
unset($_SESSION['stuff'][$temp[removeditem]]);
?>
P.S. Not tested... just a concept.

7 is value in the array not a key, so unsetting something with key 7 will not do a job.
What you have to do is compare each item in the array with one you want to delete ($_GET['item']) , retrive its key and unset it.

Related

Array_push pushes invisible element, and only works on second push

I had a problem with my array_push, that i noticed.
So what i'm doing.:
I have a site, where there are some buttons with a specific value.
Each value is getting fetched from a database.
I have a session called test, that get's converted to an array(to store multiple in the same array)
Everytime one of the buttons are clicked, the value for that specific button, is getting pushed to the array.
But, i can ONLY see that it has been pushed at the second try.
[test] => Array( [0] => 21304 )
This is what i see, after second try. But my array count, says that there are 2 elements, in that array.
Here is my code:
if(isset($_POST['process'])) {
if(!isset($_SESSION['test'])) {
$_SESSION['test'] = array();
$array_merge = array_push($_SESSION['test'], $_POST['process']);
}
}
The $_POST['process'] is the button with the unique value.
Can somebody maybe see what I'm doing wrong here?
Kind regards
You are only adding to the $_SESSION['test'] array if $_SESSION['test'] was not previously set.
So you need to always add an occurance to the session array and only initialise the session array if it was not previously set
session_start();
// ...
if(isset($_POST['process'])) {
if(!isset($_SESSION['test'])) {
$_SESSION['test'] = array();
}
$_SESSION['test'][] = $_POST['process'];
}
NOTE from the manual
If you use array_push() to add one element to the array, it's better to use $array[] = because in that way there is no overhead of calling a function.

increment value inside an array of arrays (if key is non-existent, set it to 1)

Question has been updated to clarify
For simple arrays, I find it convenient to use $arr[$key]++ to either populate a new element or increment an existing element. For example, counting the number of fruits, $arr['apple']++ will create the array element $arr('apple'=>1) the first time "apple" is encountered. Subsequent iterations will merely increment the value for "apple". There is no need to add code to check to see if the key "apple" already exists.
I am populating an array of arrays, and want to achieve a similar "one-liner" as in the example above in an element of the nested array.
$stats is the array. Each element in $stats is another array with 2 keys ("name" and "count")
I want to be able to push an array into $stats - if the key already exists, merely increment the "count" value. If it doesn't exist, create a new element array and set the count to 1. And doing this in one line, just like the example above for a simple array.
In code, this would look something like (but does not work):
$stats[$key] = array('name'=>$name,'count'=>++);
or
$stats[$key] = array('name'=>$name,++);
Looking for ideas on how to achieve this without the need to check if the element already exists.
Background:
I am cycling through an array of objects, looking at the "data" element in each one. Here is a snip from the array:
[1] => stdClass Object
(
[to] => stdClass Object
(
[data] => Array
(
[0] => stdClass Object
(
[name] => foobar
[id] => 1234
)
)
)
I would like to count the occurrences of "id" and correlate it to "name". ("id" and "name" are unique combinations - ex. name="foobar" will always have an id=1234)
i.e.
id name count
1234 foobar 55
6789 raboof 99
I'm using an array of arrays at the moment, $stats, to capture the information (I am def. open to other implementations. I looked into array_unique but my original data is deep inside arrays & objects).
The first time I encounter "id" (ex. 1234), I'll create a new array in $stats, and set the count to 1. For subsequent hits (ex: id=1234), I just want to increment count.
For one dimensional arrays, $arr[$obj->id]++ works fine, but I can't figure out how to push/increment for array of arrays. How can I push/increment in one line for multi-dimensional arrays?
Thanks in advance.
$stats = array();
foreach ($dataArray as $element) {
$obj = $element->to->data[0];
// this next line does not meet my needs, it's just to demonstrate the structure of the array
$stats[$obj->id] = array('name'=>$obj->name,'count'=>1);
// this next line obviously does not work, it's what I need to get working
$stats[$obj->id] = array('name'=>$obj->name,'count'=>++);
}
Try checking to see if your array has that value populated, if it's populated then build on that value, otherwise set a default value.
$stats = array();
foreach ($dataArray as $element) {
$obj = $element->to->data[0];
if (!isset($stats[$obj->id])) { // conditionally create array
$stats[$obj->id] = array('name'=>$obj->name,'count'=> 0);
}
$stats[$obj->id]['count']++; // increment count
}
$obj = $element->to->data is again an array. If I understand your question correctly, you would want to loop through $element->to->data as well. So your code now becomes:
$stats = array();
foreach ($dataArray as $element) {
$toArray = $element->to->data[0];
foreach($toArray as $toElement) {
// check if the key was already created or not
if(isset($stats[$toElement->id])) {
$stats[$toElement->id]['count']++;
}
else {
$stats[$toElement->id] = array('name'=>$toArray->name,'count'=>1);
}
}
}
Update:
Considering performance benchmarks, isset() is lot more faster than array_key_exists (but it returns false even if the value is null! In that case consider using isset() || array_key exists() together.
Reference: http://php.net/manual/en/function.array-key-exists.php#107786

Checking session array for value (PHP in_array)

My simple shopping cart stores products id's in a session array.
I'm trying to set up an if/else statement to enable/disable my "Add to cart" button based on the product ID being in array or not.
<?php
session_start();
//Show cart array
print_r($_SESSION['cart']);
echo '<br><br>';
//Return "yes" or "no"
$panier = $_SESSION['cart'];
$produit = "5";
if (in_array($produit, $panier)) {
print "yes man!";
}
else {
print "no man!";
}
?>
I'm making sure 5 is part of the array values by displaying them of this test page, but the second part always returns "no man!"
looks simple enough to me. What am i doing wrong ?
print_r command output is
5,5
no man!
that is because i've added 2 of the "5" product id to my cart
If I change this line
print_r($_SESSION['cart']);
for
print_r($_SESSION);
I get
Array ( [cart] => 5,3,3,3,3,3,3,3,2 )
no man!
So, according to you, $_SESSION['cart'] = "5,5"; and it means it is a string. So the right code to look up your value is strpos():
$pos = strpos($produit, $_SESSION['cart']);
if($pos !== false) {
echo "YES";
}
else {
echo "NO";
}
BUT there's a huge risk to get the wrong answer for this. Imagine, you have two products in your cart - first with id 15 and the other with id 7. You'll be looking for id 5. What would the above code output? It will output "YES".
So, instead of using a string, I suggest you use multidimensional array (if you want to stick with sessions). In this particular case then, the variable $_SESSION["cart"] would be an array and with adding new products it would look like this:
$_SESSION["cart"] = array(); // initial value, don't call it every time or it'll flush your array
$_SESSION["cart"][] = $product_ID;
Or similar to it.
print_r will give you a similarly-looking output:
Array(
cart => array(
[0] => 5
[1] => 17
[2] => 5
)
)
Then, in_array should work. But, plan your storing wisely ;)
As jon asked it is better put always the output of your program But for now I am suspecting your problem is in the in_array check this link A problem about in_array it might help

Adding a key to a foreach created array not adding all values

foreach($_POST['door_check'] as $door_check)
{
$_SESSION['front_door']['door'] = $door_check;
}
I have this little section of code that checks how many boxes were checked and then creates an array of the check box values.
The thing is, when I add that 'door' key, the array only adds one value no matter how many checkboxes were checked. When I just leave it empty, it adds all of them like [0], [1], [2] etc
Why is this?,
Your foreach() loops overwrites old variable each time. You need to make your session variable an array, for example
foreach($_POST['door_check'] as $door_check)
{
$_SESSION['front_door']['door'][] = $door_check;
}
edit: Don't forget to validate that data when you save it for later use.
Try something like this:
foreach($_POST['door_check'] as $door_check) {
$_SESSION['front_door']['door'][] = $door_check;
}
or maybe even:
$_SESSION['front_door']['door'] = $_POST['door_check'];

foreach loop corrupting my array?

Explanation
I have a multidimensional array that is iterated over to created a categorized view of people with different research interests. The main array look something like this:
Array
(
...
['Cell Biology'] => Array(4 elements)
['Molecular'] => Array(6 elements)
['Biology Education'] => Array(14 elements)
['Plant Biology'] => Array(19 elements) <--- Last element in array
)
I know that the entire array is intact and correctly structured. The only information that is inside these array is an user id, like so:
Array ('Plant Biology') 19 elements
(
[0] => 737
[1] => 742
[2] => 748
...
)
My problem is that after i run the main array through a foreach loop the last 'sub-array' gets messed up. By messed up I mean that what you see about instead look like:
String (13 characters) 'Plant Biology'
This is without doing at all anything inside the loop with to the array that gets corrupted.
Any tips to what it might be?
PHP Code
// ---> Array is OK here
echo "<h2>Research divided</h2>";
// Loop areas and list them in 2 columns
foreach($research['areas'] as $area => $areaArray) {
// ---> Here it is already corrupted
$count = count($areaArray);
if($count > 0) {
echo "<h3>$area</h3><hr/>";
echo "<ul>";
// Loop users within areas, divided up in 2 columns
for($i=0 ; $i<$count ; $i++) {
$uid = $areaArray[$i];
echo "<li>$uid</li>";
}
echo "</ul>";
}
}
Are $area or $areaArray being used in different function elsewhere in your script? Wht happens if you rename them to $loop_area and $loop_areaArray to prevent accidental overwriting of variables?
It looks like an error that can occur if you loop over the array previously by referance using the same variable name for the value.
So if earlier in your code $areaArray is used in a foreach by referance it might corrupt your data.
Make sure both variables in your foreach are not used previously or unset them before the loop.
Check out:
http://bugs.php.net/29992
For more info on this kind of problem.

Categories