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?

+2


a source to share


3 answers


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.

+1


a source


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.

+2


a source


try refresh your session

$_SESSION['files'] = $arr;

      

+1


a source







All Articles