If I have a serialized array... how can I append more values to it? Should I unserialize it first -> add data and then serialize it again?
1
-
1Obviously serializing will be the best way to go. However, if you have a huge serialized array, repeating this process over and over is going to be very inefficient. Does the array NEED to be serialized in the first place?BraedenP– BraedenP2009-11-01 22:40:35 +00:00Commented Nov 1, 2009 at 22:40
Add a comment
|
3 Answers
Yes.
function addItem($serializedArray, $item)
{
$a = unserialize($serializedArray);
$a[] = $item;
return serialize($a);
}
2 Comments
BraedenP
If he's going to be using a function, it may just be more efficient to pass $serializedArray by reference and have it append the new item directly to the referenced array rather than returning the new value and setting it again.
Ewan Todd
@BraedenP. That sounds like it could be a good improvement. I think I would also take a bit more time to name the function and its variables.
Unserializing is the way to go, definitely. Unless you have a huge string, it'd be strongly recommended, unless you want to make your own strict interpreter.
Changing anything from a serialized array/object should be done very carefully - a single extra character would break everything if you don't update all previous numbers defining each piece of structure!