Change last key name from array in php
I want to be able to change the last key from the array I am trying this function I did:
function getlastimage($newkey){
$arr = $_SESSION['files'];
$oldkey = array_pop(array_keys($arr));
$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);
$_SESSION['files'] = $arr;
$results = end($arr);
print_r($arr);
}
if i call a function getlastimage('newkey')
it changes the key! but after i type $ _SESSION the key is not changed? Why is this?
a source to share
Wow, your code is a mess!
1) You are setting $_SESSION
to a new array. For your changes to take effect, you will need to revert to the original array $_SESSION
, otherwise your new array will simply be forgotten.
2) It would be easier to just array_pop()
get the last element and set it to a new key, rather than waste time fetching all the keys and turning off the last key and then retrieving the value from the array again. The old key value is useless.
a source to share
When you install $arr = $_SESSION['files']
, you are actually making a copy $_SESSION['files']
. Everything you do with $arr
is not done with the original.
Try the following:
$arr =& $_SESSION['files'];
Notice the ampersand after the equal sign. This will make $arr
a reference before , and your updates will have an impact , since they both link to the same content. $_SESSION['files']
$arr
$_SESSION['files']
Another solution is, of course, to just copy the array, placing it $_SESSION['files'] = $arr;
at the end of your function.
a source to share