CSV To PHP Array

Login

Email
Password

Don't have an account yet?

Go to Sign up

{{ workbook ? 'Online Table Editor' : 'Input Data' }}
Change File Enter Data
Row Col Row Col
Transpose Clear Delete Empty Deduplicate
ABC abc Abc
Replace
First Row as Header
{{ displayRows.length }} rows x {{ displayHeaders.length }} columns{{ firstRowAsHeader ? ' (1 header)' : '' }} {{ selectedRows.length > 0 ? selectedRows.length + ' selected' : '' }}
Output Data
{{ copied ? 'Copied!' : 'Copy to Clipboard' }} Download File
Properties
Convert CSV to PHP online — paste, edit, and download PHP.

Convert Restart
Insert Row Below
Insert Row Above
Insert Column Right
Insert Column Left
Delete Row {{ contextMenu.row + 1 }}
Delete Column {{ contextMenu.col + 1 }}
Clear Cell
Clear Row
Case sensitive Use regex Cancel Replace All

CSV to PHP Array — Free Online PHP Code Generator

What Is PHP?

PHP is a server-side scripting language designed for web development. It powers 77% of websites with a known server-side language, including WordPress, Drupal, and Laravel applications.

<?php

$greeting = "Hello, World!";

echo $greeting;

What Is a PHP Array?

An array is PHP's most versatile data structure. It holds key-value pairs and supports both indexed and associative access.

Indexed Array

$fruits = ['Apple', 'Banana', 'Cherry'];

echo $fruits[0]; // "Apple"

echo count($fruits); // 3

Associative Array

$person = [

'name' => 'Alice',

'age'  => 30,

'city' => 'New York',

];

echo $person['name']; // "Alice"

Multidimensional Array

$users = [

['name' => 'Alice', 'age' => 30],

['name' => 'Bob',   'age' => 25],

['name' => 'Charlie', 'age' => 35],

];

echo $users[1]['name']; // "Bob"

Short Syntax [] vs Long Syntax array()

SyntaxVersionExample
Short []PHP 5.4+['name' => 'Alice']
Long array()All versionsarray('name' => 'Alice')

Short syntax is the modern standard. Use long syntax only for PHP 5.3 or legacy codebases.

fgetcsv() vs. This Tool

Using fgetcsv() (Runtime)

<?php

$rows = [];

$handle = fopen('data.csv', 'r');

$headers = fgetcsv($handle);


while (($row = fgetcsv($handle)) !== false) {

   $rows[] = array_combine($headers, $row);

}

fclose($handle);

print_r($rows);


Aspectfgetcsv()
When to useDynamic CSV files at runtime
RequiresFile path or uploaded file at runtime
FlexibilityHandles any CSV size
DependenciesCSV file must be present at runtime
PerformanceDisk I/O on every request

Using This Tool (Code Generation)

AspectThis Tool
When to useStatic data, seeders, fixtures, config
OutputSelf-contained PHP array literal
FlexibilityEditable PHP source code
DependenciesNone at runtime — data is hardcoded
PerformanceNo disk I/O; array is in memory

Using str_getcsv() (Single String)

<?php

$csv = "Alice,30,New YorkBob,25,London";

$lines = explode("", $csv);

$data = array_map(function ($line) {

   return str_getcsv($line);

}, $lines);

print_r($data);

Why Convert CSV to PHP Array?

Use CaseDescription
Laravel seedersPopulate database tables with seed data
PHPUnit fixturesDefine test data in test methods
Config filesHardcode lookup tables in config/ files
Migration dataEmbed reference data in database migrations
WordPress pluginsDefine option arrays from spreadsheet data
Drupal modulesCreate form options and taxonomy data
Shopify appsMap product data to PHP arrays
API mockingHardcode response data for testing
Data entryConvert spreadsheet data to PHP quickly
DocumentationInclude sample datasets in PHP docs

Core Features

1. Online Table Editor

After loading CSV data, an interactive spreadsheet grid lets you edit before converting:

OperationDescription
TransposeSwap rows and columns
ClearRemove all data
Delete EmptyRemove empty rows/columns
DeduplicateRemove duplicate rows
ReplaceFind and replace (with regex support)
Case transformUPPERCASE, lowercase, Title Case
Insert/deleteRight-click for row/column operations
First Row as HeaderToggle header treatment

2. Privacy by Design

All processing runs entirely in your browser. No CSV data is uploaded to any server.

How to Use?

Step 1: Load CSV Data

Choose one of two input methods:

  • Upload a file: Click "Choose File" and select a .csv file.

  • Paste data: Click "Enter Data" to switch to the code editor. Paste your CSV.

Step 2: Edit in Table Editor (Optional)

Use the toolbar to clean your data before converting.

Step 3: Enable "First Row as Header"

Toggle this ON to use the first CSV row as associative array keys.

Step 4: Convert

Click Convert. The PHP array code appears in the "Output Data" panel.

Step 5: Copy or Download

  • Click Copy to Clipboard to paste into your .php file.

  • Premium users can click Download File to save.

Complete Example — Employee Data

Input CSV:

name,department,salary,active

Alice,Engineering,95000,Yes

Bob,Marketing,78000,No

Charlie,Engineering,102000,Yes

Diana,Design,85000,Yes

Configuration:

  • First Row as Header: ON

Output:

<?php

$array = [

   ['name' => 'Alice','department' => 'Engineering','salary' => '95000','active' => 'Yes',],

   ['name' => 'Bob','department' => 'Marketing','salary' => '78000','active' => 'No',],

   ['name' => 'Charlie','department' => 'Engineering','salary' => '102000','active' => 'Yes',],

   ['name' => 'Diana','department' => 'Design','salary' => '85000','active' => 'Yes',],

];

Example — Without Headers (Indexed Array)

Input CSV:

Alice,30,New York

Bob,25,London

Charlie,35,Tokyo

Configuration:

  • First Row as Header: OFF

Output:

<?php

$array = [

   ['Alice', '30', 'New York'],

   ['Bob', '25', 'London'],

   ['Charlie', '35', 'Tokyo'],

];

Real-World Use Cases

Laravel Database Seeder

<?php

namespace DatabaseSeeders;


use IlluminateSupportFacadesDB;

use IlluminateDatabaseSeeder;


class ProductSeeder extends Seeder

{

   public function run(): void

   {

       $products = [

           ['name' => 'Laptop', 'price' => '1299.99', 'stock' => '45'],

           ['name' => 'Phone', 'price' => '699.99', 'stock' => '120'],

           ['name' => 'Tablet', 'price' => '499.99', 'stock' => '0'],

           ['name' => 'Monitor', 'price' => '399.99', 'stock' => '30'],

       ];

       DB::table('products')->insert($products);

   }

}

PHPUnit Test Fixture

<?php

namespace TestsUnit;


use PHPUnitFrameworkTestCase;


class UserValidationTest extends TestCase

{

   private array $testUsers;

   protected function setUp(): void

   {

       $this->testUsers = [

           ['name' => 'Alice', 'email' => '[email protected]', 'age' => '30'],

           ['name' => 'Bob', 'email' => '[email protected]', 'age' => '25'],

           ['name' => 'Invalid', 'email' => 'not-an-email', 'age' => '-1'],

       ];

   }

   public function test_valid_emails(): void

   {

       $validUsers = array_filter($this->testUsers, function ($user) {

           return filter_var($user['email'], FILTER_VALIDATE_EMAIL);

       });

       $this->assertCount(2, $validUsers);

   }

   }

Laravel Config File

<?php

// config/countries.php

return [

   ['code' => 'US', 'name' => 'United States', 'currency' => 'USD'],

   ['code' => 'GB', 'name' => 'United Kingdom', 'currency' => 'GBP'],

   ['code' => 'JP', 'name' => 'Japan', 'currency' => 'JPY'],

   ['code' => 'DE', 'name' => 'Germany', 'currency' => 'EUR'],

   ['code' => 'FR', 'name' => 'France', 'currency' => 'EUR'],

];

// Usage: config('countries')

WordPress Plugin Options

<?php

$shipping_zones = [

   ['zone' => 'Domestic', 'rate' => '5.99', 'free_above' => '50'],

   ['zone' => 'Europe', 'rate' => '12.99', 'free_above' => '100'],

   ['zone' => 'Worldwide', 'rate' => '24.99', 'free_above' => '200'],

];

foreach ($shipping_zones as $zone) {

   add_option('shipping_' . strtolower($zone['zone']), $zone);

}

Database Migration with Data

<?php

use IlluminateDatabaseMigrationsMigration;

use IlluminateSupportFacadesDB;


return new class extends Migration

{

   public function up(): void

   {

       $roles = [

           ['name' => 'admin', 'label' => 'Administrator'],

           ['name' => 'editor', 'label' => 'Editor'],

           ['name' => 'viewer', 'label' => 'Viewer'],

       ];

       foreach ($roles as &$role) {

           $role['created_at'] = now();

           $role['updated_at'] = now();

       }

       DB::table('roles')->insert($roles);

   }

};

Frequently Asked Questions

  • Does the tool upload my data?

    No. All conversion happens locally in your browser using JavaScript. Your CSV data never leaves your device.

  • What PHP version is the output compatible with?

    The short array syntax [] requires PHP 5.4+. For PHP 5.3 compatibility, replace [] with array().

  • What is the difference between indexed and associative arrays?

    Indexed arrays use numeric keys ($arr[0]). Associative arrays use string keys ($arr['name']). Enable "First Row as Header" to generate associative arrays; disable for indexed arrays.

  • Can I use the output in Laravel?

    Yes. Paste the generated array directly into seeders, migrations, config files, or test files. The short syntax [] is compatible with all Laravel versions.

  • What is the difference between this tool and fgetcsv()?

    fgetcsv() reads CSV files at runtime from disk. This tool generates PHP source code with hardcoded array literals. Use this tool for seed data, fixtures, and config; use fgetcsv() for dynamic CSV processing.

  • Can I edit the data before converting?

    Yes. The built-in table editor lets you modify cells, transpose, deduplicate, find/replace, change case, and insert/delete rows and columns.

  • Are CSV values type-converted?

    No. All values are output as PHP strings. Use PHP type casting ((int), (float), filter_var()) to convert types after generating the array.

  • What CSV formats are supported?

    Standard CSV with comma delimiters. The first row can be used as associative array keys (enable "First Row as Header").

Featured Tools

Featured tools that you might find useful.

Popular Tools

List of popular tools that users love and frequently use.

New Tools

The latest tools added to our collection, designed for you.

Topics

The tools grouped by topics to quickly find what you need.
Free online Excel to JSON converter. Transform XLSX, XLS, XLSM files into JSON arrays, objects, or keyed formats instantly in your browser — no upload, 100% private.

Excel To JSON

Free online Excel to JSON converter. Transform XLSX, XLS, XLSM files into JSON arrays, objects, or keyed formats instantly in your browser — no upload, 100% private.
Free Excel to CSV converter. Convert XLSX, XLS, XLSM to CSV instantly in your browser. No upload, 100% private. Edit, transpose, deduplicate before exporting.

Excel To CSV

Free Excel to CSV converter. Convert XLSX, XLS, XLSM to CSV instantly in your browser. No upload, 100% private. Edit, transpose, deduplicate before exporting.
Free online Excel to SQL converter. Generate CREATE TABLE and INSERT statements from spreadsheets for MySQL, PostgreSQL, SQLite, and SQL Server. Supports batch insert, primary keys, and type inference.

Excel To SQL

Free online Excel to SQL converter. Generate CREATE TABLE and INSERT statements from spreadsheets for MySQL, PostgreSQL, SQLite, and SQL Server. Supports batch insert, primary keys, and type inference.
Free online Excel to ASCII table converter with 10 border styles (MySQL, Unicode, reStructuredText, and more). Add code comment wrappers in 8 languages. Supports text alignment. Client-side processing.

Excel To ASCII Table

Free online Excel to ASCII table converter with 10 border styles (MySQL, Unicode, reStructuredText, and more). Add code comment wrappers in 8 languages. Supports text alignment. Client-side processing.