Home › Developer Tools › JSON to PHP Array

JSON to PHP Array

Paste JSON and get clean PHP array code with short [ ] or classic array( ) syntax, aligned => arrows, or exact var_export() output, ready for config files, seeders and tests. Switch direction to turn a PHP array literal back into JSON. Everything runs in your browser.

Last updated:

Everything is converted locally in this tab; nothing is uploaded or executed. Tip: Ctrl + Enter converts.

Advertisement
Advertisement

How to use the JSON to PHP Array

  1. Choose the direction: JSON → PHP array, or PHP array → JSON.
  2. Paste your input or open a .json or .php file. A sample is loaded so you can see the result right away.
  3. Pick the output style: short or long array syntax or var_export(), a variable or return statement, indent and alignment (or the JSON flags in reverse mode).
  4. Press Convert. With Live update on, the output refreshes as you type.
  5. Copy or download the .php or .json file, or press Swap direction to round-trip the result.

Example: JSON to PHP array

{ "name": "Ada", "admin": true, "score": 9.5, "tags": ["math", "code"], "address": { "city": "London", "zip": null } }

With the default options (short syntax, aligned arrows, trailing commas) this becomes:

$data = [
    'name'    => 'Ada',
    'admin'   => true,
    'score'   => 9.5,
    'tags'    => ['math', 'code'],
    'address' => [
        'city' => 'London',
        'zip'  => null,
    ],
];

In PHP you would get the same array from json_decode($json, true), and json_encode($data) turns it back into the original JSON.

JSON and PHP types side by side

JSONPHP (short syntax)var_export()
"text"'text''text'
"line\nbreak""line\nbreak"quoted with a real line break
42 / 4.542 / 4.542 / 4.5
true / falsetrue / falsetrue / false
nullnullNULL
[1, 2][1, 2]array ( 0 => 1, 1 => 2, )
{"a": 1}['a' => 1] or (object) ['a' => 1]array ( 'a' => 1, )
{} / [][]array ( )

Round-trip gotchas

  • Empty objects. {} and [] both decode to an empty PHP array, and json_encode([]) returns []. Keep empty objects with (object) [] or the JSON_FORCE_OBJECT flag.
  • Numeric string keys. PHP converts keys like "7" to the integer 7. If such keys happen to be 0, 1, 2 … in order, json_encode() outputs a list instead of an object.
  • Floats. Since PHP 7.1, json_encode(3.0) gives 3.0, while integers stay integers. Very large integers beyond PHP_INT_MAX become floats.
  • Escaping. By default PHP escapes slashes (\/) and non-ASCII characters (ë). Use JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE for cleaner output, as this tool does by default.

Frequently asked questions

How are JSON objects represented in PHP?

A JSON object becomes an associative array with string keys, which is what json_decode($json, true) returns. A JSON array becomes a list with keys 0, 1, 2 and so on. If you prefer stdClass objects, as json_decode($json) returns without true, turn on Objects as (object) casts.

What is the difference between [ ] and array( )?

They are identical at runtime. The short [ ] syntax has been available since PHP 5.4 and is the modern standard (PSR-12 and most frameworks use it). Choose array( ) only for very old code bases or style guides that require it.

What does the var_export() style produce?

It reproduces the exact formatting of PHP's var_export($value): array ( with a space, two-space indentation, explicit numeric keys, NULL in capitals, and floats written with a decimal point such as 3.0. This is handy for comparing with output from existing scripts or generated cache files.

How are strings escaped?

Strings are written in single quotes, where only backslash and single quote need escaping, so O'Brien becomes 'O\'Brien'. Strings with line breaks, tabs or other control characters use double quotes with \n, \t and \x escapes, and any $ is escaped so PHP does not try to interpolate variables.

How does PHP array to JSON decide between a list and an object?

It follows json_encode(): an array whose keys are exactly 0, 1, 2 … in order becomes a JSON array, and anything else (string keys, gaps or a different order) becomes a JSON object. Empty arrays become [] unless they are cast with (object) or JSON_FORCE_OBJECT is on. Keys follow PHP rules, so '7' becomes the integer 7, true becomes 1, and a duplicate key overwrites the earlier value.

Can it convert PHP code that uses variables, constants or functions?

No. Only literal values are converted: strings, numbers, true, false, null, nested arrays and (object) casts. Nothing is executed, so expressions like PHP_EOL, $name or date() are reported as errors. Replace them with literal values or run json_encode() in PHP instead.

Is my data uploaded?

No. Both directions are handled by JavaScript in this page and no PHP code is executed, so your data never leaves your device.

Are all the tools on FreeToolCabin tested for quality and accuracy?

Yes! Every tool on our site undergoes automated Q/A testing in real browser environments to ensure high precision, correct output, and zero errors. If you happen to spot a bug or have a suggestion, please contact us at [email protected] and our team will review it right away.

Related tools

JSON FormatterBeautify, minify and validate JSON, with a collapsible tree view.JSON ValidatorCheck JSON with the exact line and column of each error, fix tips and one-click auto-fix.JSON to TypeScriptGenerate TypeScript interfaces or types from JSON, with nested types and optional fields.JSON to YAML ConverterConvert JSON to clean YAML as you type, with indent, quoting and sort options.JSON to Excel ConverterTurn JSON into a styled .xlsx spreadsheet; nested arrays become their own linked sheets.JSON to CSVConvert JSON data to CSV for spreadsheets.CSV to JSONConvert CSV data to JSON with live preview.Excel to CSVConvert XLSX spreadsheets to CSV.CSV ViewerOpen a CSV or TSV file as a sortable, filterable table.Excel Viewer (XLSX / XLS)Open XLSX, XLS and ODS spreadsheets in your browser without Excel.Line Ending ConverterConvert text and files between CRLF, LF and CR line endings.Markdown to HTMLConvert Markdown to clean HTML with a live editor.XML to JSONConvert XML to JSON with validation.Text Encoding ConverterDetect and convert text file encodings like UTF-8, UTF-16 and Latin-1.JSON ViewerExplore JSON as a collapsible tree, search keys and values and copy any node's path.TTF to WOFF2 ConverterConvert TTF and OTF fonts to WOFF2 or WOFF and get a ready @font-face CSS snippet.Chmod CalculatorConvert Linux file permissions between checkboxes, octal (755) and symbolic (rwxr-xr-x) notation.Morse Code TranslatorTranslate text to Morse code and back, then play it as sound or a blinking light, or save a WAV.HTML Table GeneratorBuild HTML tables in an editable grid with styles, header rows, CSV import and live preview.Hex to Text ConverterConvert hex to text and text to hex with UTF-8 support and space, 0x, \x or comma formats.JSON to XML ConverterConvert JSON to well-formed XML with attributes, arrays and pretty print.YAML to JSON ConverterConvert YAML to pretty or minified JSON, with errors pinned to the exact line.HTML to Markdown ConverterTurn HTML or pasted rich text into clean Markdown with tables and live preview.Markdown Table GeneratorBuild Markdown tables in a grid or paste from Excel/CSV, with alignment and preview.Image to Base64Convert images to Base64 data URIs, CSS backgrounds and HTML img tags in your browser.Base64 to ImagePaste a Base64 string or data URI to preview, identify and download the image.JSON CompareCompare two JSON documents and see every added, removed and changed path.Hex to DecimalConvert hex to decimal instantly with steps and signed mode.Decimal to HexConvert decimal to hex instantly with steps and signed mode.Binary to DecimalConvert binary to decimal instantly with steps and signed mode.Decimal to BinaryConvert decimal to binary instantly with steps and signed mode.Two's Complement CalculatorDecimal to two's complement binary and back for 4-64 bits, with invert-and-add-1 steps.XML to CSV ConverterConvert XML to CSV: detects repeating records, flattens nested data, pick your columns.CSV to XML ConverterConvert CSV to well-formed XML with custom root and row names, escaping and pretty print.TOML to JSON ConverterConvert TOML to JSON and JSON to TOML with a full v1.0 parser and clear error lines.JSON to Go StructTurn JSON into Go structs with inferred types, nested structs and json tags.JSON to Python ClassGenerate Python dataclasses, Pydantic models or TypedDicts with type hints from JSON.JSON to C# ClassConvert JSON to C# classes or records with System.Text.Json or Newtonsoft attributes.Compare Excel FilesCompare two Excel spreadsheets cell by cell, highlight changes and export a diff report.CSV CleanerClean messy CSV in one click: trim spaces, drop empty rows and columns, fix headers, dedupe.CSV VLOOKUP ToolJoin two CSV or Excel files on a key column like VLOOKUP, with left, inner and full joins.Remove Duplicates in ExcelFind and remove or highlight duplicate rows in XLSX or CSV files by the columns you choose.GeoJSON ViewerView GeoJSON on a map, inspect and edit properties, validate against RFC 7946 and export.GPX ViewerOpen GPX tracks on a map with distance, elevation profile, moving time, speed and splits.JSON Repair ToolFix broken JSON automatically: trailing commas, quotes, comments, truncated data, with a diff.Karnaugh Map SolverSolve 2–6 variable K-maps: click cells or enter minterms to get the minimal SOP or POS with groups.Merge Excel FilesCombine XLSX, XLS and CSV files into one workbook or append all rows into a single sheet.Parquet File ViewerOpen Apache Parquet files in your browser: schema, rows, filters and CSV or JSON export.Query CSV with SQLRun SQL on CSV, Excel, JSON and Parquet files in your browser with DuckDB. Join and export.Online Serial MonitorTalk to Arduino, ESP32 and USB serial devices in your browser: log, send, plot and save.Split Excel FileSplit an Excel sheet into several files by row count or by each value in a column, as ZIP.SQL Create Table GeneratorDefine columns, keys, defaults and indexes; get CREATE TABLE SQL for MySQL, Postgres and more.SQL IN Clause GeneratorTurn a pasted list into a SQL IN ('a','b') clause with quoting, dedupe and 1,000-item chunks.SQL Online CompilerRun SQL queries online on SQLite with sample databases, a result grid, CSV export and .db save.SQL to ER DiagramPaste CREATE TABLE statements and get an entity-relationship diagram with keys and links.XML to XSD GeneratorGenerate an XML Schema (XSD) from sample XML: types, occurrences, attributes and namespaces.XML ValidatorCheck if XML is well-formed, see the exact line and column of each error and pretty-print it.Wildcard Mask CalculatorConvert a subnet mask or CIDR to a wildcard mask for ACLs and OSPF, with range and binary.CSV to VCF ConverterConvert a contacts CSV into a vCard (.vcf) file, mapping columns to name, phone, email and more.CSV to YAML ConverterConvert CSV rows to a YAML list of mappings with type inference and delimiter detection.Endianness ConverterSwap byte order of 16, 32 and 64-bit hex values and see big- and little-endian integers and floats.Excel to SQL ConverterTurn an Excel sheet into CREATE TABLE and INSERT statements for MySQL, PostgreSQL, SQLite or SQL Server.Excel to VCF ConverterTurn an Excel contact list into a vCard .vcf file for iPhone, Android, Google or Outlook.File to C ArrayConvert any file into a C or C++ byte array header, like xxd -i, with const and PROGMEM options.Image to C ArrayConvert images to monochrome, RGB565 or RGB888 C arrays for OLED, LCD and TFT displays.JSON Merge ToolDeep-merge two or more JSON objects with array concat, replace or union and a conflict rule.JSONL to CSV ConverterConvert JSON Lines / NDJSON to CSV with flattened columns; streams large files locally.PHP Unserialize OnlineDecode PHP serialize() strings to JSON, a tree or print_r, and serialize JSON back to PHP.
See all 129 Data & File Format Converters →