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

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)

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]);

To delete and element from an array use unset() function:
<?php
//session array O
unset(O["array"][1]);
?>

Related

How to add an element to PHP array without deleting element that is already in array?

I want to add an element to PHP array when form is submitted and then add that array to $_SESSION so I can display it on other page while $_SESSION is active, but when an element is added to an array, element that is already in it is deleted so I constantly have 1 item in array. Any suggestions?
Here's the code:
$korpa = array();
$_SESSION["korpa"] = $korpa;
if(isset($_POST["add"])){
array_push($korpa, $_POST["id"]);
}
You keep assigning an empty array to your session variable, so it will be empty at the start of your script, before you append the POST variable.
Instead, you can append directly to that session variable if the condition is met.
// Initialize the session array if its not set
if (!isset($_SESSION["korpa"])) {
$_SESSION["korpa"] = [];
}
// Then append the POST value to the session if that's set
if (isset($_POST["add"])) {
$_SESSION["korpa"][] = $_POST["add"];
}
Naturally you will need to call session_start() at the top of every page using sessions, otherwise they will not be set across your different pages.

Array index increment

I have this array in php code. I want to have that whenever page is being called it should print value of first array index and when next time second value of array index and so on... what modification I could do? for now it´s printing everything when being called single time.
<html>
<?php
$addresses = array('ifcbxespra', 'ifcheqjbmea', 'ifcqiknsa', 'ifcqirtjla', 'ifcwqsrlmn', 'ifclmkmzhz','ifcwdujhgc','ifcihddngh','icffhzudcd','ifchnsqzgs','ifcgssqrhg');
foreach ($addresses as &$value) {
echo $value ;
}
?>
</html>
I'm not sure if I understood what you want. But if you want to print the first array's value when the page loads one time, the second array's value when the page loads another time and so on, you can do this:
<?php
if(!isset($addresses) || empty($addresses)){ //checks if the array is not initialized or if it's empty
$addresses = array('ifcbxespra', 'ifcheqjbmea', 'ifcqiknsa', 'ifcqirtjla', 'ifcwqsrlmn', 'ifclmkmzhz','ifcwdujhgc','ifcihddngh','icffhzudcd','ifchnsqzgs','ifcgssqrhg');
echo $addresses[0]; //print the first value
array_splice($addresses, 0, 1); //removes the first element of the array and reindexes it
}else{
echo $addresses[0]; //print the first value
array_splice($addresses, 0, 1); //removes the first element of the array and reindexes it
}
The logic behinds it is: if the array already exists and is not empty (it has values), print the first value and then remove it, so next time the first value will be the second actual value. When the array is empty, redefine it as to start again.
You can search for more information on array_splice() here.
P.S.: you have to use PHP's $_SESSION to save the array between the pages.
You can use something like $_SESSION and store there the last index.
For example:
$array = array('one', 'two', 'three');
if (!$_SESSION['nextIndex'] || $_SESSION['nextIndex'] >= count($array)) {
$_SESSION['nextIndex'] = 0
}
// print the value
echo $array[$_SESSION['nextIndex']];
// increment the nextIndex
$_SESSION['nextIndex']++;
NOTE: This will only work for the same user. Each page reload will increment the array index. But if you need some cross-user counting, then you have to store the information somewhere on the server, like a DB or even a simple txt file.
Check out this example: http://hibbard.eu/how-to-make-a-simple-visitor-counter-using-php/
Finally I solved this problem with the MySQL. created a column with all code. and then call the script every-time when user press button. In the script first I fetch first raw and print that value, and then, delete that raw. so every-time user will get unique value from the list of code And it is working fine.

creating a new array with an element removed

I have an array of elements, e.g. (apple, orange, grapes)
Say this is an array in a variable $fruit. I want to create a new variable $new_fruit, that removes the first element, $fruit[0]
I want to be able to do this
$new_fruit = unset($fruit[0]);
Of course I cannot, if I unset $fruit[0], then its removed from $fruit, and I need all elements to remain in the element $fruit. And create a new variable without the first element.
As an alternative to the simple:
$new_fruit = $fruit;
unset($new_fruit[0]);
You can omit more than just the first one by changing the second argument:
$new_fruit = array_slice($fruit, 1);

How add value in the beginning of the array with a key?

I know about function array_unshift(), but that adds to array with a autoincrement key.
For this code:
$messages[$obj_result['from']] = $obj_result;
I need to add value $obj_result in the beginning of the array. So, last added value will be in the beginning of array.
do somthing like this
$array = array("a"=>1,"b"=>2,"d"=>array("e"=>1));
$newArray["c"] = 3;
echo "<pre>";
print_r(array_merge($newArray,$array));
in array_merge first argument will be your that key value pair that you want to add in beginning.
Assuming as an array (with your desire key) you can use operator + :
$messages = obj_result + $messages;
From the manual:
while literal keys won't be touched
So you can just prepend the element, assuming the from key of the $obj_result variable is a string, all the key's will stay the same, while your new element is still on the beginning of the array.

Check if element is in array, but exclude array's last element?

How to check if a string is already in array, but during checking exclude last element of that array? By now, I'm using a workaround with unset() and re-declaration like this:
$fkTableName = $fkTableArr[$colNr0];
unset($fkTableArr[$colNr0]);
if (!in_array($fkTableName, $fkTableArr))
// do sth
$fkTableArr[$colNr0] = $fkTableName;
but it seems pretty redundant to me.
Use array_slice() to slice the array and use it. The below code doesn't include the last element in the array.
array_slice($input, -1);
So your code becomes:
$fkTableName = $fkTableArr[$colNr0];
if (!in_array($fkTableName, array_slice($fkTableArr, -1)))
// do sth
If you want to not affect the array, try this:
if (in_array($fkTableName, $fkTableArr) && $fkTableName != end($fkTableArr)) {
// element in array, but not last item
}

Categories