how to unset a session variable? - php

I have the following code, but it does not work, I don't know what mistake I am committing due to which this code does not work:
Here is the code:
<?php session_start();
if (isset($_GET['indexNo']) && is_numeric($_GET['indexNo']) && !empty($_GET['indexNo']))
{
$indx = $_GET['indexNo'];
foreach($_SESSION['itemsOrder'] as $key => $val)
{
echo "$key => $val <br> " ;
if($indx == $val)
{
unset($_SESSION['itemsOrder'][$val]);
}
else
{
echo "indexNo was not unset <br>";
}
}
}
else
{
echo "indexNo not received!";
}
?>

Should be $key not the $val . Try with -
if($indx == $key)
{
unset($_SESSION['itemsOrder'][$key]);
}
No need to use isset & empty together.
if (isset($_GET['indexNo']) && is_numeric($_GET['indexNo']))

You need to unset the session array value than you must use its key instead of value.
replaced:
unset($_SESSION['itemsOrder'][$val]);
with:
unset($_SESSION['itemsOrder'][$key]);

**Try This Code**
<?php session_start();
if (isset($_GET['indexNo']) && is_numeric($_GET['indexNo']))
{
$indx = $_GET['indexNo'];
foreach($_SESSION['itemsOrder'] as $key => $val)
{
echo "$key => $val <br> " ;
if($indx == $val)
{
unset($_SESSION['itemsOrder'][$key]);
}
else
{
echo "indexNo was not unset <br>";
}
}
}
else
{
echo "indexNo not received!";
}

Related

Add values to $_SESSION['name'] then Loop thru values

I'm using a $_SESSION variable to store error codes in an app I'm creating.
On my form processing page, i'm using the following code (as an example):
session_start();
$_SESSION['site_msg'] = array();
if(1 == 1) {
$_SESSION['site_msg'] = 18;
}
if(2 == 2) {
$_SESSION['site_msg'] = 21;
}
if(3 == 3) {
$_SESSION['site_msg'] = 20;
}
I'm hoping to use a function to get the values from the array to use elsewhere in my code.
function error_code() {
foreach($_SESSION['site_msg'] as $value) {
echo "Value: $value <br />";
}
}
The above gives an error; Warning: Invalid argument supplied for foreach() ...
If I write the function like this:
$array[] = $_SESSION['site_msg'];
foreach($array as $value) {
echo "VAL: " . $value;
}
It only gives me the last value, 20.
Anyone have an idea where I went wrong?
Thanks!
<?php
session_start();
$_SESSION['site_msg'] = array();
if(1 == 1) {
array_push($_SESSION['site_msg'],18); // '=' overwrites the data, so push data in session array not to assign
}
if(2 == 2) {
array_push($_SESSION['site_msg'],21);
}
if(3 == 3) {
array_push($_SESSION['site_msg'],20);
}
$array = $_SESSION['site_msg']; //remove [] from variable, its not needed
foreach($array as $value) {
echo "VAL: " . $value;
}
?>
You declare your variable $_SESSION['site_msg'] as an array, but you pass integer values to this variable! You need to add your values as new array elements.
This should work:
session_start();
$_SESSION['site_msg'] = array();
if(1 == 1) {
$_SESSION['site_msg'][] = 18;
}
if(2 == 2) {
$_SESSION['site_msg'][] = 21;
}
if(3 == 3) {
$_SESSION['site_msg'][] = 20;
}
As an alternative you can use the function array_push() to add your values to the array:
session_start();
$_SESSION['site_msg'] = array();
if(1 == 1) {
array_push($_SESSION['site_msg'], 18);
}
if(2 == 2) {
array_push($_SESSION['site_msg'], 21);
}
if(3 == 3) {
array_push($_SESSION['site_msg'], 20);
}

PHP, Echo only one time in a foreach loop

i'have an array, and then i have a script who gets the category i'm browsing (using wordpress) and put it in the $category variable.
So i test if the category i'm browsing it's equal to the $array key and then i paste some text
$array = array ('key' => 'value', ... )
//...
// a script who gets the category i'm browsing and store it in the $category variable
//...
/* starting the foreach loop */
foreach( $array as $key => $value) {
if ($category == $key) {
echo "some $value here";
} elseif ($category !== $key) {
echo "nothing";
}
The problem is that this loop does echo "nothing" for each time the $category is not equal to the $key for each element of the array.
So if i have 20 key => value in the array this loop paste one time "some $value here" and 19 times "nothing"
there is a way to echo "nothing" only one time?
Thank you!
You can use array_key_exists instead of the foreach loop:
if (array_key_exists($category, $array)) {
echo $array[$category];
} else {
echo 'nothing';
}
$i=0;
foreach( $array as $key => $value) {
$i++;
if ($category == $key) {
echo "some $value here";
} elseif($category !== $key)
{
if($i<=1)
{
echo "nothing";
}
else{}
}
Try with -
$i = 1;
foreach( $array as $key => $value) {
if ($category == $key) {
echo "some $value here";
} elseif ($category !== $key) {
$i++;
}
}
if (count($array) == $i) {
echo "nothing";
}

Using an if statement to alter a foreach loop

I've got a loop. It echoes each item in an array. However, I want to wrap one of the items with some custom content. At the moment, I can do that, but it repeats it unnecessarily. Here is my loop:
$arr = array(1,2,3,4,5,6);
foreach ($arr as $key) {
if ($key == 5) {
echo 'wrap';
echo $key;
echo 'wrap';
}
echo $key;
}
Which produces:
1
2
3
4
WRAP
5
WRAP
5 <--- remove
6
As you can see, the $key 5 is being duplicated. I just need to wrap it once when it's called. Is there a way to only echo 5 once?
As it's currently written, the echo statement after your if block will get executed on each loop iteration. You only want that to happen when the value of $key is not 5. So use the else block:
foreach ($arr as $key) {
if ($key == 5) {
echo 'wrap';
echo $key;
echo 'wrap';
} else {
echo $key;
}
}
What about this:
$arr = array(1,2,3,4,5,6);
foreach ($arr as $key) {
if ($key == 5) {
echo 'wrap';
echo $key;
echo 'wrap';
} else {
echo $key;
}
}
Yep, simple, just add an 'else' statement:
$arr = array(1,2,3,4,5,6);
foreach ($arr as $key) {
if ($key == 5) {
echo 'wrap';
echo $key;
echo 'wrap';
} else {
echo $key;
}
}

loop through $_POST variables with similar names

I have several $_POST variables, they are
$_POST['item_number1']
$_POST['item_number2']
and so on
I need to write a loop tha displays the values of all the variables (I don't know how many there are). What would be a simplest way to go about it? Also what would be the simplest way if I do know how many variables I have?
This will echo all POST parameters whose names start with item_number:
foreach($_POST as $k => $v) {
if(strpos($k, 'item_number') === 0) {
echo "$k = $v";
}
}
PHP Manual: foreach(), strpos()
If you know how many do you have:
for ($i=0; $i < $num_of_vars; $i++)
echo $_POST['item_number'.$i]."<br />";
UPDATE:
If not:
foreach($_POST as $k => $v) {
$pos = strpos($k, "item_number");
if($pos === 0)
echo $v."<br />";
}
Gets all POST variables that are like "item_number"
UPD 2: Changed "==" to "===" because of piotrekkr's comment. Thanks
try:
foreach($_POST as $k => $v)
{
if(strpos($k, 'item_number') === 0)
{
echo "$k = $v";
}
}
In the above example, $k will be the array key and $v would be the value.
if you know the number of variables:
<?php
$n = 25; // the max number of variables
$name = 'item_number'; // the name of variables
for ($i = 1; $i <= $n; $i++) {
if (isset($_POST[$name . $i])) {
echo $_POST[$name . $i];
}
}
if you don't know the number:
<?php
$name = 'item_number';
foreach ($_POST as $key) {
if (strpos($key, $name) > 0) {
echo $_POST[$key];
}
}
If you must stick with those variable names like item_numberX
foreach (array_intersect_key($_POST, preg_grep('#^item_number\d+$#D', array_keys($_POST))) as $k => $v) {
echo "$k $v \n";
}
or
foreach (new RegexIterator(new ArrayIterator($_POST), '#^a\d+$#D', null, RegexIterator::USE_KEY) as $k => $v) {
echo "$k $v \n";
}
Better to use php's input variable array feature, if you can control the input names.
<input name="item_number[]">
<input name="item_number[]">
<input name="item_number[]">
then php processes it into an array for you.
print_r($_POST['item_number']);
foreach($_POST as $k => $v) {
if(preg_match("#item_number([0-9]+)#si", $k, $keyMatch)) {
$number = $keyMatch[1];
// ...
}
}
try:
while (list($key,$value) = each($_POST))
${$key} = trim($value);

loop through posted values to see if any equal "no"

How can i loop through a post and find if any of the answers are "no"?
Here is my code so far:
if($_POST["minRequirementsForm"]) {
foreach($_POST as $key => $value) {
$_SESSION['minrequirements'][$key] = $value;
}
}
Thanks in advance.
You could use in_array() or array_search() and save a loop:
if (in_array('no', $_POST)) echo 'they said no'.
if (($key = array_search('no', $_POST)) !== false) echo "$key was answered with no";
if($_POST["minRequirementsForm"]) {
foreach($_POST as $key => $value) {
if ('no' == $value) {
// do something
}
$_SESSION['minrequirements'][$key] = $value;
}
}
$NoAsnwers = false;
if($_POST["minRequirementsForm"]) {
foreach($_POST as $key => $value) {
if ($value == 'No') $NoAsnwers = true;
}
}
Maybe so?

Categories