p9jwtq
Last Updated: February 25, 2016
·
1.32K
· mdotobie

Setting Values using RecursiveArrayIterator::offsetSet

It appears that when you use the RecursiveArrayIterator::offsetSet() method to change a value within a JSON object you are iterating over that the new value needs to be of the same type as the original value. I imagine more often than not, at least when dealing with JSON iteration, that the value will be an object or an array because the iterator treats the object like an array. If you try to set it to another data type (i.e. string, integer, etc), PHP will throw a:

Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Passed variable is not an array or object, using empty array instead'

My workaround has been to use RecursiveArrayIterator::offsetUnset first to nullify the old value and its type and then call RecursiveArrayIterator::offsetSet() to set the new value.

2 Responses
Add your response

17243

Thanks ;)

over 1 year ago ·
17245

Could you provide a sample code for iteration over JSON and modifying its values. I fail to do that. Much appreciated!

over 1 year ago ·