Get your next remote job on LaraJobs.
1 contributor Edit on GitHub PHP

Easily convert a PHP array to JSON

Table of contents:

Easily convert a PHP array to JSON

Convert a PHP array to JSON

To convert a PHP array to JSON, you can use the json_encode() function. Here’s how it’s done:

$array = [
"foo" => "bar",
"baz" => "qux",
$json = json_encode($array);
echo $json;

Running the above code snippet will output: {"foo":"bar","baz":"qux"}. And just like that, your PHP array is now a JSON string!

Let’s unwrap the mystique around json_encode():

  • json_encode() is a function that converts a PHP value into a JSON value. This can be done for arrays, objects, and even simple data types like strings, booleans, and integers.
  • JSON is an acronym for JavaScript Object Notation, but don’t let the name fool you - it can be used beyond JavaScript. It’s a lightweight data-interchange format that’s easy for humans to read and write and easy for machines to parse and generate.

When to convert a PHP array to JSON

Here are some of the use cases I met where you would need to convert PHP arrays to JSON format:

  • Data exchange: You may need to convert PHP arrays to JSON when exchanging data between a server and a web application (before JSON was invented, it was XML).
  • Storing data: Since JSON is a lightweight and readable format, it’s commonly used to store complex data structures.
  • Work with modern APIs: Most modern APIs such as those for social media platforms and cloud services communicate using JSON, so converting your PHP array to JSON can be necessary to work with these APIs.

Catching array to JSON conversion errors

PHP also provides a function to inspect the last occurred error during JSON encoding/decoding.

$array = [
"foo" => "bar",
"baz" => "qux",
$json = json_encode($array);
if (json_last_error() !== JSON_ERROR_NONE) {
echo json_last_error_msg();

If something unexpected happens during the JSON encoding, you can get the last error message using json_last_error_msg().

But this is an old-fashioned way of doing it if you ask me. You could also simply ask PHP to throw an exception when something goes wrong using the JSON_THROW_ON_ERROR constant:

try {
$array = [
"foo" => "bar",
"baz" => "qux",
$json = json_encode($array, JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
Benjamin Crozat

Written by Benjamin Crozat

Indie hacker, blogger, and AI enthusiast building things with the TALL stack. 🔥

Follow me on:

Recommended articles

Print an array with PHP (+ Laravel) Print an array with PHP (+ Laravel)

Debugging requires dissecting everything. Here's a list of all the one-line of code built-in ways to print arrays in PHP (and even Laravel-specific helpers).

Modified on Jun 24, 2023

PHP 8.3 is out, now! Here's what's new and changed. PHP 8.3 is out, now! Here's what's new and changed.

PHP 8.3 was released on November 23, 2023, and as usual, you need to be up to date with new features and breaking changes for easier transitions.

Modified on Nov 23, 2023

7 Laravel RESTful APIs best practices for 2023 7 Laravel RESTful APIs best practices for 2023

Master the art of crafting RESTful APIs with Laravel thanks to these best practices.

Modified on Oct 10, 2023

The fastest way to check if your PHP array is empty The fastest way to check if your PHP array is empty

There are multiple ways to check if an array is empty. Let me tell you about each of them and why and when you should use them.

Modified on Nov 2, 2023 Audio available


Gold sponsors New

  • Wire Elements
    Beautiful handcrafted Livewire components.
    Check site
Your business here


If you buy from one of my partners below, I will be compensated at no cost to you. These are services I use or used, and 100% stand behind.

  • Scalable and reliable VPS hosting.
    Bonus: $200 of free credits
    Check site
  • The Google Analytics alternative without compromise.
    Free trial: 30 days
    Bonus: $10 off your first invoice
    Check site
  • Flare
    Track PHP and JavaScript errors in one place.
    Free trial: 10 days
    Check site
  • Keep track of your Google rankings.
    Free trial: 7 days
    Promo code: WELCOME30
    Check site
- / -