I see that people store arrays as like:
a:6:{i:0;s:5:\"11148\";i:1;s:5:\"11149\";i:2;s:5:\"11150\";i:3;s:5:\"11153\";i:4;s:5:\"11152\";i:5;s:5:\"11160\";}
I've not seen this a whole lot. But it's clearly done for implementation ease. Serializing data allows to store quasi binary data.
Your second example is a CSV
scheme. This is workable for storing confined string lists. While it's easier to query or even modify within the database, it makes more effort for unmarshalling from/to the database API. Also there is really only limited list
support anyway. http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_find-in-set
However, true, the serialized data is unneeded in your example. It's only a requirement if you need to store complex or nested array structures. And in such cases the data blob is seldomly accessed or queried within the database.
With serialize and unserialize you are using native php functions that run faster than php based loop constructs etc. serialize and unserialize are the way to go if you absolutely positively have to store an array in the db (like for sessions). Otherwise you may want to reconsider your application design to not store php array in the database. It may cause problems down the road if you try to access the data with a language other than php.
there is no mysql type array, and the reason is so you can recreate the array easily, if your data was as you showed it not hard but what about a multidimensional array with non numeric keys. Of course this is NOT good db practice in the first place, breaking normilisation
It's because PHP has the serialize() function that takes a PHP array and turns it into a string like the one you quoted above, and then has another function, unserialize(), that takes the array string and converts it back into a PHP array.
This makes it very easy to turn an array into a string when it needs saving in a database and then turn it back into a proper PHP array after you select it from the database later.
See the PHP manual here: http://php.net/serialize
and: http://php.net/unserialize
One thing you can't do with CSV notation (1,2,3,4
) is represent multi-dimensional arrays.
Neither way is really appropriate though. The data should be normalized into separate related tables. If there's a real need to store serialized data in a database that can't be or doesn't need to be normalized, it should be stored as JSON, which is language independent and smaller.