Dutchcoffee Dutchcoffee - 1 year ago 64
PHP Question

PHP Update Serialized Data

I need some help with unserializing and updating the array values and reserializing them (using php). Basically I want to be able to unserialize a string, update the value for a specific key (without loosing the other values) and reserialize it. I've searched and can't seem to find a viable solution (or maybe I'm just typhlotic).

The array I'm trying to update is very simple. It has a key and value.

array (
'key' => 'value',
'key2' => 'value2',

I currently have, but it does not work.

foreach(unserialize($serializedData) as $key => $val)
if($key == 'key')
$serializedData[$key] = 'newValue';

$updated_status = serialize($serializedData);


You can't write directly to the serialized data string like you are trying to do here:

$serializedData[$key] = 'newValue';

You meed to deserialize the data to an array, update the array, and then serialize it again. It seems as if you only want to update the value if the key exists, so you can do it like this:

$data = unserialize($serializedData);
if(array_key_exists('key', $data)) {
    $data['key'] = 'New Value';
$serializedData = serialize($data);