Convert php array to csv string

Convert php array to csv string

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Preserving Leading Zeros and Handling Delimiters When Converting PHP Arrays to CSV

Converting a multidimensional PHP array into a CSV string is a routine task, but it often runs into specific edge cases that standard implementations miss. One of the most common pitfalls involves preserving leading zeros in numeric strings, such as mobile numbers (e.g., 01727499452). Standard formatting logic frequently strips these characters because PHP treats them as octal prefixes or simply normalizes integers to their canonical form.

To address this, you must ensure your data is treated strictly as strings before any transformation occurs. Furthermore, the delimiter handling in your custom function needs scrutiny regarding whitespace and enclosure logic.

The Leading Zero Problem

The core issue with mobile numbers like 01727499452 disappearing lies in how PHP handles numeric conversion. If a variable is cast to an integer, the leading zero is interpreted as part of the number's value, not its representation. Consequently, 01727499452 becomes 1727499452.

When generating CSV output, you must guarantee that the data remains a string type throughout the process. In your specific case, the input array contains these values correctly as strings (e.g., '01727499452'). However, if any preprocessing step casts them to int or float, the zero is lost immediately.

The solution is simple but critical: never rely on implicit casting. Ensure your $field variable remains a string. If you are reading from a database where columns might be defined as integers, you must explicitly cast the value back to a string before appending it to the output array:

$field = (string) $field;

This explicit cast ensures that 01727499452 stays exactly as is, regardless of PHP's internal numeric normalization rules.

Analyzing the Custom CSV Function

Your current implementation attempts to handle delimiters and whitespace but introduces a subtle bug in the output generation logic. Specifically, look at this line within your loop:

$output[] = $field." ";

This appends a space after every single field value. In a CSV file, fields are separated by delimiters (like commas or semicolons), not spaces. If your delimiter is ; or ,, having an extra space before the delimiter results in malformed data that parsers will reject. The trailing space should be removed unless it is part of the intended content (which is rare for phone numbers).

Additionally, your regex pattern checks for delimiters and whitespace to decide whether to enclose a field in quotes:

if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
    // ...
}

While this logic is sound for quoting, the implementation of the enclosure itself has a flaw. You are replacing the enclosure character inside the string with two of them:

$field = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;

This works correctly for doubling quotes inside a quoted field (the standard CSV escape mechanism). However, combined with the trailing space issue mentioned above, your output will likely look like Name ; Value ; 0172... instead of Name;Value;0172....

Corrected Implementation Logic

To fix the leading zero issue and the spacing bug simultaneously, you should modify your loop to strip the trailing space and ensure strict string handling. Here is a refined approach that addresses the specific constraints of your data:

function arrayToCsv(array $fields, $delimiter = ',', $enclosure = '"', $encloseAll = false) {
    $outputString = "";
    
    foreach($fields as $tempFields) {
        $output = [];
        
        foreach ($tempFields as $field) {
            // Ensure the field is treated as a string to preserve leading zeros
            if (!is_string($field)) {
                $field = (string)$field; 
            }

            // Enclose fields containing delimiter, enclosure or whitespace
            if ($encloseAll || preg_match("/(?:${delimiter}|${enclosure}|\s)/", $field)) {
                // Escape existing enclosure characters by doubling them
                $field = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
            }

            // Do not add a trailing space here; let the delimiter handle separation
            $output[] = $field; 
        }
        
        $outputString .= implode($delimiter, $output) . "\r\n";
    }
    
    return $outputString;
}

Handling Mobile Numbers Specifically

If you are dealing with mobile numbers where the leading zero is semantically significant (as it represents the national destination code), treating them as integers is never the right choice. Even if your database stores them as integers, retrieve them as strings or cast them immediately upon retrieval.

In Laravel, for instance, you might access a column and cast it explicitly:

$phone = (string) $row['mobile_number'];

This guarantees that 01727499452 remains intact when passed to your CSV generator. If you use the default comma delimiter, ensure your locale settings do not interfere with decimal points if you were handling currency alongside phone numbers, though for pure text data like contacts, this is rarely an issue.

By stripping the accidental whitespace and enforcing string types, your CSV output will accurately represent the contact list, preserving every digit of the mobile number exactly as entered.

Our network