mrkrstphr's blog

twitter github

PostgreSQL arrays and PHP's str_getcsv()

Posted on 05 Mar 2010

Yesterday, while trying to figure out the best way to deal with PostgreSQL arrays in PHP, I came across the new str_getcsv() function in PHP as of 5.3. This function works much the same as fgetcsv to parse a CSV line, except that it works on a string instead of a file.

For quick reference, CSV looks like this:

"My Name",14,"32,000","2009-04-15"

And the return value of a PostgreSQL array looks like this:

{"My Name",14,"32,000","2009-04-15"}

Notice the similarities?

We can use PHP’s trim and str_getcsv to turn this PostgreSQL array into a PHP array:


$data = str_getcsv(trim($record->value, '{}'));

Simple as simple does. As long as your array has only a single dimension. If you’re using multidimensional arrays in PostgreSQL then you’re dead to me.


The Clean Architecture in PHP

I've written a book on the Clean Architecture in PHP, which covers how to cleanly organize and decouple your code in a way that prepares it to survive and be easy to maintain for the long term.

Check it out!