PHP Serialized Update Data

I need some help unserializing and updating array values ​​and reinitializing them (using php). Basically, I want to be able to unserialize a string, update the value for a specific key (without losing other values), and reinitialize it. I have searched and cannot find a viable solution (or maybe I am just a typhlotic).

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

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

      

I currently have it, but it doesn't work.

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

$updated_status = serialize($serializedData);

      

+3


source to share


2 answers


You cannot write directly to a serialized data string like you are trying to do here:

$serializedData[$key] = 'newValue';

      



You need to deserialize the data into an array, update the array, and then serialize it again. It seems that 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);

      

+7


source


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



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

      

+5


source







All Articles