deepak asai
deepak asai

Reputation: 232

How to remove a single element from a PHP session array?

I am having a php session array like

('10/01/2017, '13/02/2017', '21/21/2107')

Now how to add and element or remove an element from this array in O(1)

Upvotes: 0

Views: 3664

Answers (2)

Jerodev
Jerodev

Reputation: 33186

The easiest way is to get the value, remove the item, and set the session variable again.

$data = $_SESSION['array'];    // Get the value
unset($data[1]);               // Remove an item (hardcoded the second here)
$_SESSION['array'] = $data;    // Set the session value with the new array

Update:
Or like @Qirel said, you can unset the item directly if you know the number.

unset($_SESSION['array'][1]);

Update 2
If you want to remove the element by its value, you can use array_search to find the key of this element. Note that if there are to elements with this value, only the first will be removed.

$value_to_delete = '13/02/2017';
if (($key = array_search($value_to_delete, $_SESSION['array'])) !== false)
    unset($_SESSION['array'][$key]);

Upvotes: 2

Chukwu Remijius
Chukwu Remijius

Reputation: 323

To delete and element from an array use unset() function:

 <?php
  //session array O
  unset(O["array"][1]);
 ?>

Upvotes: 0

Related Questions