0

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)

2
  • Which element do you want to remove, or what do you want to add? Commented Jun 12, 2017 at 14:07
  • You need either unset(), array_shift() or array_pop(), depending on what you want to do. Commented Jun 12, 2017 at 14:07

2 Answers 2

2

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]);
Sign up to request clarification or add additional context in comments.

6 Comments

Why not just unset($_SESSION['array'][1]);?
I mean, yours will work and achieve the same result - but its an extra two lines ;-)
I do not know the index value.. i jus to want to delete rhe element say '13/02/2017'.. How can i do that..?
Thank you soo much
|
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.