Question: I have trouble reading Postgresql arrays in PHP. I have tried explode(), but this breaks arrays containing commas in strings, and `str_getcsv()` but it's also no good as PostgreSQL doesn't quote the Japanese strings.

Not working:

```
explode(',', trim($pgArray['key'], '{}'));
str_getcsv( trim($pgArray['key'], '{}') );

```

Example:

```
// print_r() on PostgreSQL returned data: Array ( [strings] => {または, "some string without a comma", "a string, with a comma"} )

// Output: Array ( [0] => または [1] => "some string without a comma" [2] => "a string [3] => with a comma" ) 
explode(',', trim($pgArray['strings'], '{}'));

// Output: Array ( [0] => [1] => some string without a comma [2] => a string, with a comma ) 
print_r(str_getcsv( trim($pgArray['strings'], '{}') ));

```

Answer: 
If you can foresee what kind text data you can expect in this field, you can use `array_to_string` function. It's available in 9.1

E.g. I exactly know that my array field `labes` will never have symbol `'\n'`. So I convert array `labes` into string using function `array_to_string`

```
SELECT 
  ...
  array_to_string( labels, chr(10) ) as labes
FROM
  ...

```

Now I can split this string using PHP function `explode`:

```
$phpLabels = explode( $pgLabes, "\n" );

```

You can use any sequence of characters to separate elements of array.

SQL:

```
SELECT
  array_to_string( labels, '<--###DELIMITER###-->' ) as labes

```

PHP:

```
$phpLabels = explode( '<--###DELIMITER###-->', $pgLabes );

```
A simple and fast function for converting deep PostgreSQL array string to JSON string without using pg connection.

```
function pgToArray(string $subject) : array
{
    if ($subject === '{}') {
       return array();
    }
    $matches = null;
    // find all elements; 
    // quoted: {"1{\"23\"},abc"} 
    // unquoted: {abc,123.5,TRUE,true} 
    // and empty elements {,,}
    preg_match_all( '/\"((?<=\\\\).|[^\"])*\"|[^,{}]+|(?={[,}])|(?=,[,}])/', $subject,$matches,PREG_OFFSET_CAPTURE);
    $subject = str_replace(["{","}"],["[","]"],$subject); // converting delimiters to JSON
    $matches = array_reverse($matches[0]);
    foreach ($matches as $match) {
        $item = trim($match[0]);
        $replace = null;
        if ((strpos($item,"{") !== false) || (strpos($item,"}") !== false)) {
            // restoring replaced '{' and '}' inside string
            $replace = $match[0];
         } elseif (in_array($item,["NULL","TRUE","FALSE"])) {
            $replace = strtolower($item);
         } elseif ($item === "" || ($item[0] !== '"' && !in_array($item,["null","true","false"]) && !is_float($item))) {
            $replace = '"' . $item . '"'; // adding quotes to string element
         }
         if ($replace) { // concatenate modified element instead of old element
            $subject = substr($subject, 0, $match[1]) . $replace . substr($subject, $match[1] + strlen($match[0]));
         }
     }
     return json_decode($subject, true);
  }

```