unsetting a variable - php

I have some code here which looks as following:
if (isset($_SESSION['addToCart'])) {
foreach ($_SESSION["addToCart"] as &$value){
if ($value['titel'] == $titel){
$value['aantal'] = $aantal;
if($value['aantal'] == 0){
unset($value);
}
}
}
}
so when 'aantal' = 0, I want to delete that record, but it doesn't, it just gives back the result and 'aantal' is 0 instead of the record being removed from the session.
Anyone know what I'm doing wrong?

According to the PHP docs (http://php.net/manual/en/function.unset.php), a variable that is passed by reference is only destroyed in the local context. Try $value = null;

From the manual: "When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed."
You'd want to do something like this:
foreach ($_SESSION['addToCart'] as $key => &$value) {
if ($value['aantal'] == 0) {
unset($_SESSION['addToCart'][$key]);
}
}
Think of it like filesystem's symbolic links. When you destroy a symbolic link, it doesn't destroy the file it was linked to.

Your problem may stem from the fact that $value is a value variable, a copy of the $_SESSION["addToCarT"][current_index]. You should be setting the $_SESSION["addToCart"][current_index] to null or unsetting that, not the copies variable in the limited scope.

Related

array_push does not add value in case of used inside of foreach > if

I'm currently working on a website for my project, but for some reason when everything is as it has to be ( session is started, session variable is defined ), then only array_push() function doesn't add the value to session variable, when I move array_push() out of if, foreach and if (if contains foreach and foreach contains another if), it works fine, I already tried to put it to first if, then to foreach but it didn't help. So it works only when it is out of that code (When it is not in that if, which contains foreach, which contains another if). Please try to understand, my English is not well.
What do I have to do to fix it?
if(isset($_GET["setLang"])) {
foreach ($languages as $item) {
if($item === $_GET["setLang"]) {
$_SESSION["selLang"] = $item;
array_push($_SESSION["sessionMessage"], "Language changed successfully!");
header("location: index.php?path=/");
exit();
}
}
}
Since the code work correctly out of the if statement , it's cleary evident that the condition cause the problem
$item === $_GET["setLang"]
Using triple = will check value and type . So may be the type of each ones is different than other .
Replace it with :
$item == $_GET["setLang"] // only use two =

Checking variable is in URL then defining

I'm trying to do a simple function here, but it's not working.
I want to check if the variable is indeed in the URL, and if it is I want to define a variable with it.
if(isset($_GET['ref'])){
$ref = $_GET['ref'];
}
Could someone point out the errors?
It's probably that isset only checks if the variable has been declared. That variable could still be empty. so this will set $ref even when $_GET['ref'] = ""; Try this instead:
if(isset($_GET['ref'])){
if(!empty($_GET['ref'])))
{
$ref = $_GET['ref'];
}
}
The Get and Post variables are accessible to you as Arrays. I would loop over the array and treat it as a Key/Value pair. This will give you the ability to do what ever you would like with the key and the value.
foreach($_POST as $key=>$value)
{
echo "$key=$value";
}
See this previous Stack Overflow thread.
How do I get the key values from $_POST?

Put all parameters from a session into variables

I have the following code:
if(isset($_SESSION["spgrund"])) {
$spgrund = $_SESSION["spgrund"];
}else{
$spgrund = '';
}
This code is repeated about 20 times for each session variable. How can I make a loop out of it?
foreach($_SESSION as $key => $value){
$$key = $value;
}
I think that should work. But I get undefined variable error messages. Can't I use such a loop?
What you actually try to achieve is already available in PHP, the extract­Docs function:
extract($_SESSION);
From it's documentation:
Import variables from an array into the current symbol table.
Checks each key to see whether it has a valid variable name. It also checks for collisions with existing variables in the symbol table.
You would still need look for undefined variables however. Probably you should define them first?
foreach($_SESSION as $key => $value)
{
$$key = $value;
}
you missed the $ for value

PHP: setting session variables through variable variables

I would like to set a session variable with something akin to:
$key = '_SESSION[element]';
$$key = 'value';
This does indeed set $_SESSION['element'] equal to value, but it also seems to clear the rest of my $_SESSION variable, resulting in the $_SESSION array only containing the new key/value pair.
How can I write into the session using variable variables without nuking it?
Edit: if this can't be done, so be it, we'll probably have to restructure and do things the "right" way. I just wanted to know if there was an easy fix
#Mala, I think eval will help you.
Check the code below. It may help you for what you want.
session_start();
$_SESSION['user1'] = "User 1";
$_SESSION['user2'] = "User 2";
$key = "_SESSION['user3']";
eval("\$$key = 'User 3';");
foreach ($_SESSION as $key=>$value){
echo $key." => ".$value."<br/>";
unset($_SESSION[$key]);
}
session_destroy();
If you still have any trouble, Let me know. Thank you
From PHP Documentation:
Please note that variable variables cannot be used with PHP's
Superglobal arrays within functions or class methods. The variable
$this is also a special variable that cannot be referenced
dynamically.
How you ended up with a situation like this, is really questionable. You're probably doing something wrong.
EDIT
This little trick should give you what you want:
$key = '_SESSION[element]';
$key = str_replace(array('_SESSION[', ']'), '', $key);
$_SESSION[$key] = 'value';
var_dump($_SESSION);
This will basically produce the same results as xdazz's answer
Isn't this way better?
$key = 'element';
$_SESSION[$key] = 'value';

Delete from array help

I have a cookie which stores info in an array.
This is for a classifieds website, and whenever users delete their 'ads' the cookie must also be removed of the ad which was deleted.
So I have this:
if (isset($_COOKIE['watched_ads'])){
$expir = time()+1728000;
$ad_arr = unserialize($_COOKIE['watched_ads']);
foreach($ad_arr as $val){
if($val==$id){ // $id is something like "bmw_m3_10141912"
unset($val);
setcookie('watched_ads', serialize($ad_arr), $expir, '/');
}
}
}
This doesn't work... any idea why? I think its a problem with the unset part...
Also, keep in mind if there is only one value inside the array, what will happen then?
Thanks
You got two bugs here: 1) you unset the $val instead of the array element itself. 2) You set the cookie within the loop to the unknown $ad_arr2 array.
foreach($ad_arr as $key => $val){
if($val==$id){ // $id is something like "bmw_m3_10141912"
unset($ad_arr[$key]);
}
}
setcookie('watched_ads', serialize($ad_arr), $expir, '/');
array_filter seems appropriate:
$array = array_filter($array, create_function('$v', 'return $v != '.$id.';'));
You are correct that you are using unset incorrectly. The manual on unset states:
If a static variable is unset() inside
of a function, unset() destroys the
variable only in the context of the
rest of a function. Following calls
will restore the previous value of a
variable.
When you use 'as' you're assigning the value of that array element to a temporary variable. You want to reference the original array:
foreach ($ad_arr as $key => $val)
...
unset($ad_arr[$key]);
...

Categories