0

I add values to an associative array with this code:

$tokenarray += [$datetime => $newtoken];

This works fine. But after I sort the array and shift it with that code:

$sortedarray = krsort($tokenarray, 1);
$shiftedarray = array_shift($sortedarray);
$shiftedarray += [$datetime => $newtoken];
$tokenarrayjson = json_encode($shiftedarray);

This error appears:

Fatal error: Uncaught Error: Unsupported operand types in SITE Stack trace: #0 {main} thrown in SITE on line

$shiftedarray += [$datetime => $newtoken]; <- This line throes the error

Can someone tell my why please? Does array_shift make an object out of my array and if so, how can I prevent it?

Regards, Andreas

1 Answer 1

4

krsort does not return the sorted array, it sorts its argument in-place and returns true/false dependent on whether it succeeds or not. The same applies to array_shift, which returns the value shifted off the array, not the array post shift: You need to do this instead:

$sortedarray = $tokenarray;
krsort($sortedarray, SORT_NUMERIC);
$shiftedarray = $sortedarray;
array_shift($shiftedarray);
$shiftedarray += [$datetime => $newtoken];
$tokenarrayjson = json_encode($shiftedarray);

If you don't actually need the intermediate arrays, you can simplify that to:

krsort($tokenarray, SORT_NUMERIC);
array_shift($tokenarray);
$tokenarray += [$datetime => $newtoken];
$tokenarrayjson = json_encode($tokenarray);

Note

Since your keys are numeric strings, array_shift will interpret them as numbers and renumber your array starting from 0. To avoid this, use unset on the first key of the array (found using key) instead:

krsort($tokenarray, SORT_NUMERIC);
unset($tokenarray[key($tokenarray)]);
$tokenarray += [$datetime => $newtoken];
$tokenarrayjson = json_encode($tokenarray);

Also note that you should use SORT_NUMERIC instead of 1, just in case the value changes in a future version of PHP.

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

2 Comments

Nick, im sorry for bothering you, but can you tell me if there is a way to echo a variable of php in the browsers console? I work with javascript ajaxs so when I test it I don´t see whats going on in the php-file.
@Andreasschnetzer When I want to do that I usually include an extra field in the JSON I return from my ajax call (e.g. 'status' => 'here is a message') and then in my JS I use something like if ('status' in result) alert(result.status);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.