5

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);
2
  • You shouldn't be changing $serializedData as this is the serialized representation of your array. Save the result of your call to unserialise() and use this instead. That should do the trick. Commented Jan 21, 2013 at 19:48
  • serialized data is just a string. you're actually trashing your string with that $serializedData[$key] business. Commented Jan 21, 2013 at 19:51

2 Answers 2

8

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);
Sign up to request clarification or add additional context in comments.

Comments

6

Exactly, how you described it: Unserialize, update, serialize.

$data = unserialize($serializedData);
$data['key'] = 'newValue';
$updated_status = serialize($data);

Comments

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.