5

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
  • 1
    Obviously 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? Commented Nov 1, 2009 at 22:40

3 Answers 3

14

Yes.

function addItem($serializedArray, $item)
{
   $a = unserialize($serializedArray);
   $a[] = $item;
   return serialize($a);
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@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.
3

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!

Comments

0

yes, this is the only (reliable) way

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.