Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 687
Dutchcoffee Avatar asked Jan 21 '13 19:01

Dutchcoffee


1 Answers

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

$serializedData[$key] = 'newValue';

You need 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);
like image 155
Mike Brant Avatar answered Oct 01 '22 22:10

Mike Brant