How to remove a variable from a PHP session array - php

I have PHP code that is used to add variables to a session:
<?php
session_start();
if(isset($_GET['name']))
{
$name = isset($_SESSION['name']) ? $_SESSION['name'] : array();
$name[] = $_GET['name'];
$_SESSION['name'] = $name;
}
if (isset($_POST['remove']))
{
unset($_SESSION['name']);
}
?>
<pre> <?php print_r($_SESSION); ?> </pre>
<form name="input" action="index.php?name=<?php echo $list ?>" method="post">
<input type="submit" name ="add"value="Add" />
</form>
<form name="input" action="index.php?name=<?php echo $list2 ?>" method="post">
<input type="submit" name="remove" value="Remove" />
</form>
I want to remove the variable that is shown in $list2 from the session array when the user chooses 'Remove'.
But when I unset, ALL the variables in the array are deleted.
How I can delete just one variable?

if (isset($_POST['remove'])) {
$key=array_search($_GET['name'],$_SESSION['name']);
if($key!==false)
unset($_SESSION['name'][$key]);
$_SESSION["name"] = array_values($_SESSION["name"]);
}
Since $_SESSION['name'] is an array, you need to find the array key that points at the name value you're interested in. The last line rearranges the index of the array for the next use.

To remove a specific variable from the session use:
session_unregister('variableName');
(see documentation) or
unset($_SESSION['variableName']);
NOTE:
session_unregister() has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Is the $_SESSION['name'] variable an array? If you want to delete a specific key from within an array, you have to refer to that exact key in the unset() call, otherwise you delete the entire array, e.g.
$name = array(0 => 'a', 1 => 'b', 2 => 'c');
unset($name); // deletes the entire array
unset($name[1]); // deletes only the 'b' entry
Another minor problem with your snippet: You're mixing GET query parameters in with a POST form. Is there any reason why you can't do the forms with 'name' being passed in a hidden field? It's best to not mix get and post variables, especially if you use $_REQUEST elsewhere. You can run into all kinds of fun trying to figure out why $_GET['name'] isn't showing up the same as $_POST['name'], because the server's got a differnt EGPCS order set in the 'variables_order' .ini setting.
<form blah blah blah method="post">
<input type="hidden" name="name" value="<?= htmlspecialchars($list1) ?>" />
<input type="submit" name="add" value="Add />
</form>
And note the htmlspecialchars() call. If either $list1 or $list2 contain a double quote ("), it'll break your HTML

If you want to remove or unset all $_SESSION 's then try this
session_destroy();
If you want to remove specific $_SESSION['name'] then try this
session_unset('name');

Currently you are clearing the name array, you need to call the array then the index you want to unset within the array:
$ar[0]==2
$ar[1]==7
$ar[2]==9
unset ($ar[2])
Two ways of unsetting values within an array:
<?php
# remove by key:
function array_remove_key ()
{
$args = func_get_args();
return array_diff_key($args[0],array_flip(array_slice($args,1)));
}
# remove by value:
function array_remove_value ()
{
$args = func_get_args();
return array_diff($args[0],array_slice($args,1));
}
$fruit_inventory = array(
'apples' => 52,
'bananas' => 78,
'peaches' => 'out of season',
'pears' => 'out of season',
'oranges' => 'no longer sold',
'carrots' => 15,
'beets' => 15,
);
echo "<pre>Original Array:\n",
print_r($fruit_inventory,TRUE),
'</pre>';
# For example, beets and carrots are not fruits...
$fruit_inventory = array_remove_key($fruit_inventory,
"beets",
"carrots");
echo "<pre>Array after key removal:\n",
print_r($fruit_inventory,TRUE),
'</pre>';
# Let's also remove 'out of season' and 'no longer sold' fruit...
$fruit_inventory = array_remove_value($fruit_inventory,
"out of season",
"no longer sold");
echo "<pre>Array after value removal:\n",
print_r($fruit_inventory,TRUE),
'</pre>';
?>
So, unset has no effect to internal array counter!!!
http://us.php.net/unset

Try this one:
if(FALSE !== ($key = array_search($_GET['name'],$_SESSION['name'])))
{
unset($_SESSION['name'][$key]);
}

Simply use this method.
<?php
$_SESSION['foo'] = 'bar'; // set session
print $_SESSION['foo']; //print it
unset($_SESSION['foo']); //unset session
?>

Related

How to pass an array to another page with PHP?

I have an array which looks like:
$diseases= [
['letter' => 'A' , 'options' => "<div ..."],
....
];
And I pass the letter as a parameter in the URL. It works. But I can't understand how to make it print the options that correspond to the letter on the page. Thanks for reading.
You could put it in the session:
session_start();
$_SESSION['array_name'] = $array_name;
Or if you want to send it via a form you can serialize it:
<input type='hidden' name='input_name' value="<?php echo htmlentities(serialize($array_name)); ?>" />
$passed_array = unserialize($_POST['input_name']);
Try something like this:
<?php
$diseases = [
'A' => "<div>A</div>",
'B' => "<div>B</div>",
];
$letterAction = isset($_GET['letterAction']) ? $_GET['letterAction'] : ''; //if the letterAction parameter is defined in the URL, then get it's value
if (isset($diseases[$letterAction])) {
//if the letterAction is available in the array, then print it's value
//i.e. isset($diseases["A"]) would return true but isset($diseases["C"]) would return false in this case
echo $diseases[$letterAction];
}
You can use sessions to store information to be used on all pages:
session_start();
$_SESSION['diseases'] = $diseases; // store information to key data
On the other pages you use:
session_start();
print_r($_SESSION['diseases']);
If you only want the data to be set for 1 specific page you can use http_build_query()
$diseases = ['diseases' => $diseases];
$str = http_build_query($diseases);
echo "<a href='yourpage.php?$str'>click</a>";
Now on the next page you simply use:
parse_str($_GET['diseases'], $diseases);
print_r($diseases);

Add values and keys to session and store each individual addition (php)

I am at my wits end for last three days.
What i want to do is to code shopping-cart like functionality. So, i have two inputs that i want EACH to store in its own array.
something along the lines of:
<?php
session_start();
$input1 = [];
$input2 = [];
if(isset($_POST['submit']))
{
$input1 = $_POST['first'];
$input2 = $_POST['second'];
$_SESSION['test'] = [
'first' => array_push($input1),
'second' => array_push($input2)
];
}
var_dump($_SESSION['test']);
?>
and my html is as follows :
<form method="post">
<input type="text" name="first" value="">
<input type="text" name="second" value="">
<input type="submit" name="submit" value="array">
</form>
Now i expect the output of var_dump to be as follows:
Array(
[First] => ('Random1','Random2')
[Second] => ('Flower1','Flower2')
)
But what i get in the best case is:
Array(
[First] => Random1
[Second] => Flower1
[0] => Random2
[1] => Flower2
)
So, my question is 1) How can i add values to $_SESSION['test'] as an array
and 2) How can i store each input in it's corresponding array?
array_push takes at least two parameters: an array, and something to push into it. You're giving it the one input, and then are not pushing anything into it. Further, you're replacing your entire $_SESSION['test'] on every run, overwriting it with new (nonsense) values.
What you want is:
$_SESSION['test']['first'][] = $input1;
$_SESSION['test']['second'][] = $input2;
Append something to the end of the existing arrays, not overwrite them.

Sending html array to a PHP form

This is my actual code. I am trying to send the array "sku" which has copied the original array of "parent..." to php with $_post. But no matter what I try it won't send.
<script>
var sku = new Array();
for (q=1;q<parent.item_num;q++)
{
sku[q] = parent.itemlist[q].code;
}
</script>
Please help.
If the name attribute is something like name="item[]", then $_POST['item'] is an array, so you can use foreach loop to go through all items.
If your form method is post you can use <?php $_POST['item'] ?> to access the array.
You can also use foreach to loop through all of the items:
<?php
foreach($_POST['item'] as $item){
... do something with $item ...
}
?>
Arrays in HTML, e.g.
<input type="text" name="arr[]" id="arr1" />
<input type="text" name="arr[]" id="arr2" />
simply create arrays under their normal $_GET/$_POST variables, so, var_dump($_REQUEST['arr']) would yield:
arr => array(
[0] => "whatever was in arr1",
[1] => "whatever was in arr2"
)
maybe this will help :
$id = 4;
if (isset($_POST['item_'.$id]))
{
item[$id] = $_POST['item_'.$id];
} else {
item[$id] = 0;
}
PS : slugonamission way seems more appropriate

in_array giving Warning Message

All,
I have the following code:
$qry = "Select * from vendor_options order by vendor_option_name ASC";
$result = mysql_query($qry);
while($resultset = mysql_fetch_array($result)){
if(isset($_SESSION['pav_choosen_vendor_categories'])){
for($z=0;$z<$_SESSION['pav_choosen_vendor_categories'];$z++){
$sVendorId = $_SESSION['pav_vendor_categories_' . $z];
if($sVendorId==$resultset['vendor_option_id']){
$vendor_cats_choosen[] = $sVendorId;
}
}
if(in_array($resultset['vendor_option_id'],$vendor_cats_choosen)){
?>
<input type="checkbox" value="<?php echo $resultset['vendor_option_id']; ?>" class="select_vendor" name="vendor_categories[]" checked><?php echo $resultset['vendor_option_name']; ?><br>
<?php
}else{
?>
<input type="checkbox" value="<?php echo $resultset['vendor_option_id']; ?>" class="select_vendor" name="vendor_categories[]"><?php echo $resultset['vendor_option_name']; ?><br>
<?php
}
}
}
I'm trying to check to see if the value returned in the mysql_fetch_array is already in my array. Say the first value it finds in the array is in the fourth iteration of the while loop. I'll get the following error:
Warning: in_array() expects parameter 2 to be array, null
Once it gets to a value that is in the array the rest of them work fine. Why does itgive an error for the first couple? Thanks.
It looks like you have not initialized $vendor_cats_chosen to be an array, and so if the condition if($sVendorId==$resultset['vendor_option_id']) is not true, no elements will be appended to it, turning it implicitly into an array.
Initialize it before the while loop. You should just about always initialize arrays before use.
// Initialize the array
$vendor_cats_chosen = array();
while($resultset = mysql_fetch_array($result)){
....
Now, when your in_array() statement executes, the array may be empty, but will be a valid array.
// $vendor_cats_chosen might be an empty array, or may have elements.
if(in_array($resultset['vendor_option_id'],$vendor_cats_choosen)){
The problem is that your array not always creates. To fix this issue just add
$vendor_cats_choosen = array();
somewhere before while in your code.
You only ever populate the array $vendor_cats_choosen inside an if statement, which means it can potentially contain no values. You also do not declare it before you start the loop which populates it - which you should do anyway, because adding a value to an undeclared array will emit an E_NOTICE.
Add the line
$vendor_cats_choosen = array();
...at the top of the script and the error will disappear. If you think this array should contain values, you may need to examine the logic in your if statement.
In order to eliminate the warning message, two approaches can be followed:
1) use of # before the statement which is generating the warning message ( However, this is not an advisable engineering approach )
2) prior to using the array object, it can be filtered out in an if-else.
For example, in your case, you can add this line
if( $vendor_cats_choosen ){
if(in_array($resultset['vendor_option_id'],$vendor_cats_choosen)){
?>
<input type="checkbox" value="<?php echo $resultset['vendor_option_id']; ?>" class="select_vendor" name="vendor_categories[]" checked><?php echo $resultset['vendor_option_name']; ?><br>
<?php
}else{
?>
<input type="checkbox" value="<?php echo $resultset['vendor_option_id']; ?>" class="select_vendor" name="vendor_categories[]"><?php echo $resultset['vendor_option_name']; ?><br>
<?php
}
} ?>

How do I echo each value of a foreach loop?

Not sure if the question title actually makes sense.
Anyway, what I'd like to do is be able to echo an individual value from a foreach loop.
Here's my code:
$headlines = array('primary_headline' => $_POST['primary_headline'], 'secondary_headline' => $_POST['secondary_headline'], 'primary_subline' => $_POST['primary_subline'], 'secondary_subtext' => $_POST['secondary_subtext']);
$city_name = "Dallas";
$ref_name = "Facebook";
$searches = array('$city_name', '$ref_name');
$replacements = array($city_name, $ref_name);
if(isset($headlines)) {
foreach($headlines as $headline) {
$headline = str_replace($searches, $replacements, $headline);
echo($headline['primary_headline']); // I thought this would do the trick
}
}
I thought that this would've echoed my city is Dallas when my city is $city_name was posted, unfortunately, this isn't the case and it merely echoes msps, which is the first letter of each input value:
<input name="primary_headline" type="text" value="my city is $city_name" />
<input name="secondary_headline" type="text" value="secondary headline" />
<input name="primary_subline" type="text" value="primary subline" />
<input name="secondary_subtext" type="text" value="secondary subline" />
<input type="submit" value="submit" />
If anyone could point me in the right direction, it would be very much appreciated!! :)
$searches = array('$city_name', '$ref_name');
The single quotes are making $searches literally contain the word $city_name, not the VALUE of $city_name. You don't need quotes while assigning variables:
$searches = array($city_name, $ref_name);
unless, of course, you're doing some kind of templating system and trying to do variable interpolation without eval().
Change
echo($headline['primary_headline']); // I thought this would do the trick
To
echo($headline) . PHP_EOL; // I thought this would do the trick
When you are using foreach you do not need to specify an index to the element, because foreach will handle iterating for you, so when you dereference something inside the loop, you are asking for a character from the string. Here you get the first character because 'primary_headline' is being interpreted as a 0.
$headlines = array('primary_headline' => $_POST['primary_headline'], 'secondary_headline' => $_POST['secondary_headline'], 'primary_subline' => $_POST['primary_subline'], 'secondary_subtext' => $_POST['secondary_subtext']);
This creates an array with key=>value pairs, not a multidimensional array. Looping through this array in a foreach loop will return only the values, i.e. $_POST['primary_headline'] for the first iteration, $_POST['secondary_headline'] for the second iteration, etc. This is why you're unable to access $headline['primary_headline'].
If you want to access "my city is Dallas" per your example, simply echo $headlines['primary_headline'].
If you want to echo each value:
foreach($headlines as $headline) {
echo $headline . PHP_EOL;
}
For good measure figured I should close this question with an answer (I've already placed it in the comments section as I couldn't add an answer).
The ampersand (&) must be used in order to assign a reference to the original array $headlines instead of copying it's valuables, thus updating it with any values created within the foreach() loop.
So, my code is now;
$headlines = array('primary_headline' => $_POST['primary_headline'], 'secondary_headline' => $_POST['secondary_headline'], 'primary_subline' => $_POST['primary_subline'], 'secondary_subtext' => $_POST['secondary_subtext']);
$city_name = "Dallas";
$ref_name = "Facebook";
$searches = array('$city_name', '$ref_name');
$replacements = array($city_name, $ref_name);
if(isset($headlines)) {
foreach($headlines as &$headline) {
$headline = str_replace($searches, $replacements, $headline);
}
echo ($headlines['primary_headline']) // This now has the value of $_POST['primary_headline'] along with the str_replace() function assigned to $headline
}

Categories