Basically I have a session value that will get updated periodically, but I need to save the previous value of the session.
Here is what I have got so far:
$value = $_GET['value'];
$_SESSION["prev-value"] = $_SESSION["value"];
$_SESSION["value"] = $value;
And the problem of course is that when I go to do <?php echo $_SESSION["prev-value"]; ?> it will be overwritten by the new value as we are checking if it is equal to the new value.
I don't want to have to store previous values in a database or text file, would that be the only way or is there any way to get past that?
Side Note:
I only need the last value, so I don't need to keep a massive lot, just the value before the newest
Do it only when you are having the GET parameter to set it. Technically you should be using POST to update or change values in the server side, which includes sessions.
if (isset($_GET['value'])) {
$value = $_GET['value'];
$_SESSION["prev-value"] = $_SESSION["value"];
$_SESSION["value"] = $value;
}
With the above way, unless you have /?value=something, your session value will not be affected.
Update: With your comments, it looks like it's worth trying out having previous values as an array. So slightly change your $_SESSION["prev-value"] as an array.
if (isset($_GET['value'])) {
$value = $_GET['value'];
if (!isset($_SESSION["prev-value"]))
$_SESSION["prev-value"] = array();
$_SESSION["prev-value"][] = $_SESSION["value"];
$_SESSION["value"] = $value;
}
This way, you would have a history of previous values that are iterable and you don't need a Database or a Text File. :) Even if the same values get set too many times, you can use the PHP function array_unique() to get the unique values of array and if you are crazy, array_reverse() it and get the second [1] value for the previous one. ;)
To get the previous one, what you might need to do is this:
$lastValue = array_reverse(array_unique($_SESSION["prev-value"]));
if (count($lastValue) > 1)
$lastValue = $lastValue[1];
echo $lastValue;
Set previous value as blank first time. and change your code as
$_SESSION["prev-value"] = $_SESSION["value"] ?? '';
$_SESSION["value"] = $_GET['value'];
Flow of code
$_SESSION["prev-value"]---------------$_SESSION["value"]
""---------------10 ----->First time load
10---------------20 ----->Next time load
20---------------30 ----->Next time load
......
......
Related
I'm kinda lost here.
So here is what i'm trying to do.
I have a session, that's called "test", i have set the session to be an array every time that $_POST['process'] isset.
The $_POST['process'] is containing a integer, that's fetched from a DB Table.
Here's my code:
if(isset($_POST['process']))
{
$_SESSION['test'] = array();
$array_merge = array_push($_SESSION['test'], $_POST['process']);
}
It work's at first time, here's the result:
[test] => Array
(
[0] => 21311
)
I was expecting, that it would create a new key, and assign it to the other value that get's fetched from $_POST['process'] - but instead it just overwrites the 0 key.
What am i doing wrong here?
Kind regards
In your code you're writing $_SESSION['test'] = array(); which is resetting the value of $_SESSION['test'] to an empty array. Therefore it has removed your previous value and have put in your new one.
To fix this check if $_SESSION['test'] is already set, if it's not do $_SESSION['test'] = array();, otherwise just insert new values.
Full example:
if(isset($_POST['process'])) {
if(!isset($_SESSION['test'])) {
$_SESSION['test'] = array();
}
$array_merge = array_push($_SESSION['test'], $_POST['process']);
}
Honestly, this is one precise case where using array_push() is a disadvantage versus its alternative square bracket syntax.
array_push() requires you to declare the empty array in advance; [] will not AND it is functionless AND it is more brief to code.
Furthermore, I am nearly 100% sure that you don't actually want to know the new element count after pushing. The PHP Manual says:
Returns the new number of elements in the array.
...so, if you do want to know the new count, then perhaps rename your variable from $array_merge to $array_size or $array_count or $array_length.
I know I wouldn't want to write an extra condition just to declare an empty variable then use a function to add a new element, especially when it can be done in one line
if(isset($_POST['process'])) {
$_SESSION['test'][] = $_POST['process']; // all done
}
This will work the first time and every time as desired.
Is there a way to execute a code only when my array has a new value passed on in position [0];?
if(?){
print_r(array_values($parcels)[0]);
} else{}
tried multiple statements but all lead to error or invalid. If a new order comes in array[0] gets replaced with that info. So only when that info has changed execute this.. Is this Possible?
You need to store the old value in an other variable to compare it. So you are able to consider if the value has changed.
$oldValue = $parcels[0];
//-------
//Code that eventually changes the array
//-------
if($oldValue != $parcels[0]) {
print_r(array_values($parcels)[0]);
$oldValue = $parcels[0];
} else{}
So i'm having trouble getting a bit of code to work. Essentially what I want to do is:
in a foreach loop, if a given array value is set, compare that existing value to the current loop value, then set the existing value = current value (for the iteration) if the existing value is already greater than current val. Here is the code i'm working with:
if ($usedebayxml->ack == 'Success') {
foreach($usedebayxml->searchResult->item as $key => $value) {
if(isset($newarray[1]['TotalCost'])) {
if($newarray[1]['TotalCost'] > ((integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice)) {
$newarray[1]['Title'] = (string)$value->title ;
$newarray[1]['ShippingCost'] = (integer)$value->shippingInfo->shippingServiceCost;
$newarray[1]['Price'] = (integer)$value->sellingStatus->currentPrice;
$newarray[1]['Condition'] = 'New';
$newarray[1]['TotalCost'] = (integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice;
}
}
else
$newarray[1]['Title'] = (string)$value->title;
$newarray[1]['ShippingCost'] = (integer)$value->shippingInfo->shippingServiceCost;
$newarray[1]['Price'] = (integer)$value->sellingStatus->currentPrice;
$newarray[1]['Condition'] = 'Used';
$newarray[1]['TotalCost'] = (integer)$value->shippingInfo->shippingServiceCost + (integer)$value->sellingStatus->currentPrice;
}
}
With this code, what is returned is ultimately the values in the LAST key object in the xml file (im using simpleXML if that helps). In other words, i don't think the first if block (if isset) is being entered into, and the values are being set to whatever the values are for the current iteration. Can anyone see any flaw in my logic here? I've been stumped on this one for a while.
I am a supreme idiot. The logic here is fine, i was just missing a { for the opening else block. dur! After adding this, this bit of code works as intended :)
I'm surprised though that i wasn't throwing any errors without having this....I think that was probably throwing me off in determining why it wasn't working originally.
public function action_adicionar_item()
{
$lista_item_pedido = array();
$x = 0;
if(Session::has('lista_item_pedido'))
{
foreach(Session::get('lista_item_pedido') as $item)
{
$lista_item_pedido[$x] = $item;
$x++;
}
}
$lista_item_pedido[$x] = Input::all();
Session::put('lista_item_pedido', $lista_item_pedido);
}
The first time I ran this method, the session is not created so the if is ignored and it sets the array value and should define the session with name a value but it doesn't.
The second time I call it, the session is created but with no values, what is weird.
Any ideas why on my first run the session is created with the empty array?
Input::all() is returning the correct values.
I have checked the file storage/sessions/ the file is created and the value is set correctly:
s:17:"lista_item_pedido";a:1:{i:0;a:7:{s:2:"id";s:3:"162";s:10:"referencia";s:12:"112233445566";s:9:"descricao";s:6:"Sapato";s:5:"grade";s:14:"Grade 41 ao 46";s:8:"grade_id";s:1:"4";s:5:"valor";s:5:"50.00";s:10:"fornecedor";s:2:"30";}}}s:13:"last_activity";i:1340395110;}
This is created the first time I run the method, so it is created but I can't access it, only when I add two values and in this case, the first is ignored.
Try using $_SESSION instead...
OK so I'm making something to do some data mining but I do changes to an array (by overwritting previous array values) in a loop and they show that they've been changed but once I get outside of a greater loop the values change back to their original values.
Probably easier to give an example:
It starts off like this, turning a bunch of the parts of the array into the word "MATCH".
Now if I was to immediately dump the values of the array it would show that some values have changed to "MATCH" (ie, right after changing the value I would echo the array slot and it would show it's value to be "MATCH") However after I get outside the loop the array changes back to it's original contents
Here is a compressed version of the code:
//i've got this big loop for doing the main work
do {
//Set dat ticker
$q = 0;
// Run through entire previous scrape array to check for matches and mark them as unchanged
do {
if ($itemTitle[$i] == $prodURLS[$q]) {
$prodURLS[$q] = "MATCH";
echo "When the value is printing immediately it shows that it's changed: ".$prodURLS[$q]."<br>";
}
$q++;
} while ($q < $urlArraySize);
$i++;
} while ($i < $itemtitleArraySize);
//If I were to try to print the variable down here it would be reverted to like it was before I changed it to "MATCH"
print_r($prodURLS);
From running your code, setting the variables as follow, it works for me:
$prodURLS = array('a','b','c');
$itemTitle = array('a');
$urlArraySize = count($prodURLS);
$itemtitleArraySize = count($itemTitle);
$i = 0;
My only recommendations with only this amount of information, are:
To provide more context information, as madth3 suggests.
To check the scope in which you are setting/checking values. You may need the & operator to pass variables by reference, or the global keyword to use global variables.
To use the foreach loop, it will make your code smaller and easier to read. Also you won't need to count the size of the arrays and will have other advantages, e.g. in the use of associative arrays. Again, be careful about the use of variables by reference. For example:
foreach ($itemTitle as $item) {
foreach ($prodURLS as &$prod) {
if ($item == $prod) {
$prod = 'MATCH';
}
}
}
unset($prod); //Unset variable set by reference if you are going to use it later on!
Also, you may find useful some of the php array functions like array_walk. Check out the PHP Manual on the array functions reference.
Really, there isn't a lot that can be said from just the code you provided.
Good luck.