tags:

views:

135

answers:

3

i want to be able to change the last key from array i try with this function i made:

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 the function getlastimage('newkey') it change the key!but after if i print the $_SESSION the key is not changed? why this?

+1  A: 

try update the session

$_SESSION['files'] = $arr;
Puaka
+2  A: 

When you set $arr = $_SESSION['files'], you are actually making a copy of $_SESSION['files']. Everything you do to $arr is not done to the original.

Try this:

$arr =& $_SESSION['files'];

Note the ampersand after the equals sign. That will make $arr a reference to $_SESSION['files'], and your updates to $arr will affect $_SESSION['files'] as well, since they both reference the same content.

The other solution is of course to just copy the array back by putting $_SESSION['files'] = $arr; at the end of your function.

zombat
+1  A: 

Wow, your code is a mess!

1) You're setting $_SESSION in a new array. In order for your changes to take affect, you'll need to set back to your original $_SESSION array, otherwise your new array will just be forgotten.

2) It would be easier to simply array_pop() to get the last element and set it to the new key, rather than wasting the time to fetch all the keys and pop the last key off, then fetch the value from the array again. The old key value is worthless.

animuson