Viewed   101 times

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?

 Answers

2
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.

Monday, September 12, 2022
3

Here is another way. No intermediate variables are saved.

We used this to de-duplicate results from a variety of overlapping queries.

$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
Tuesday, December 27, 2022
3

Store them as arrays, that way you can access the quantity using the ID as a key:

$_SESSION['quantity'][$id] = $quantity;

So instead of storing your ID and Quantity in two separate strings, you have them in one array, with the ID as the key. Converting your example above your array will look like this:

array(
    1    => 3
    4    => 4
    6    => 5
);

Then if you wanted to add / adjust anything you just set $id and $quantity to the appropriate values and use the line above.

Wednesday, December 14, 2022
5

If you work with register_globals enabled, any array-item in $_SESSION is also known as a variable by that key:

With register_globals on:

<?php
session_start();
var_dump($products);

Should show you the unserialized string. Because you later say $products = array(); you are implicitly altering $_SESSION['products']. Solution: disable register_globals, and on a side note: you don't need to serialize that data, a session can hold multi-dimensional arrays just fine. Just make sure to have any needed class-definitions loaded before calling session_start, or have an autoload function.

Thursday, August 4, 2022
 
3

Here's a sample class you can run that I believe does what you're looking for. Removing rows from 2D arrays is tricky business because like @KalebBrasee said, you can't really "remove" them, but rather you have to make a whole new 2D array instead. Hope this helps!

import java.util.ArrayList;
import java.util.List;

public class Matrix {
    private double[][] data;

    public Matrix(double[][] data) {
        int r = data.length;
        int c = data[0].length;
        this.data = new double[r][c];
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                this.data[i][j] = data[i][j];
            }
        }
    }

    /* convenience method for getting a
       string representation of matrix */
    public String toString() {
        StringBuilder sb = new StringBuilder(1024);
        for (double[] row : this.data) {
            for (double val : row) {
                sb.append(val);
                sb.append(" ");
            }
            sb.append("n");
        }

        return (sb.toString());
    }

    public void removeRowsWithValue(final double value) {
        /* Use an array list to track of the rows we're going to want to
           keep...arraylist makes it easy to grow dynamically so we don't
           need to know up front how many rows we're keeping */
        List<double[]> rowsToKeep = new ArrayList<double[]>(this.data.length);
        for (double[] row : this.data) {
            /* If you download Apache Commons, it has built-in array search
              methods so you don't have to write your own */
            boolean found = false;
            for (double testValue : row) {
                /* Using == to compares doubles is generally a bad idea
                   since they can be represented slightly off their actual
                   value in memory */
                if (Double.compare(value, testValue) == 0) {
                    found = true;
                    break;
                }
            }

            /* if we didn't find our value in the current row,
              that must mean its a row we keep */
            if (!found) {
                rowsToKeep.add(row);
            }
        }

        /* now that we know what rows we want to keep, make our
           new 2D array with only those rows */
        this.data = new double[rowsToKeep.size()][];
        for (int i = 0; i < rowsToKeep.size(); i++) {
            this.data[i] = rowsToKeep.get(i);
        }
    }

    public static void main(String[] args) {
        double[][] test = {
                {1, 2, 3, 4, 5, 6, 7, 8, 9},
                {6, 2, 7, 2, 9, 6, 8, 10, 5},
                {2, 6, 4, 7, 8, 4, 3, 2, 5},
                {9, 8, 7, 5, 9, 7, 4, 1, 10},
                {5, 3, 6, 8, 2, 7, 3, 7, 2}};

        //make the original array and print it out
        Matrix m = new Matrix(test);
        System.out.println(m);

        //remove rows with the value "10" and then reprint the array
        m.removeRowsWithValue(10);
        System.out.println(m);
    }
}
Saturday, November 12, 2022
 
rudolfv
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :