How to use json_encode and json_decode in php

json_encode and json_decode are php functions for working with JSON strings.

Converting Array to JSON

json_encode takes an array as a parameter and converts it to JSON.

let’s test it.


$productManufacturers = array(
    "iPhone 12" => "Apple",
    "Samsung Galaxy S21" => "Samsung",
    "Google Pixel 5" => "Google",
    "Sony PlayStation 5" => "Sony",
    "Apple MacBook Pro" => "Apple"

$json = json_encode($productManufacturers);

here it returns this JSON string:

'{"iPhone 12":"Apple","Samsung Galaxy S21":"Samsung","Google Pixel 5":"Google","Sony PlayStation 5":"Sony","Apple MacBook Pro":"Apple"}'

we can pass a second parameter as a flag to json_encode function. these flags are predefined PHP constants.

some of the constants:





for example, if we use JSON_NUMERIC_CHECK, the numeric strings will be encoded as numbers.

first, we use json_encode without the flag.

$numbers = [
    'row1' => '12454',
    'row2' => '5223',
    'row3' => '48.2',
    'row4' => '478',
$json = json_encode($numbers);


look at the result:

all the numeric values are strings now.

let’s use the JSON_NUMERIC_CHECK flag:

$numbers = [
    'row1' => '12454',
    'row2' => '5223',
    'row3' => '48.2',
    'row4' => '478',

$json = json_encode($numbers,JSON_NUMERIC_CHECK);


the quotation marks are removed and numeric values are shown as numbers.

you can see the full list of PHP Json Constants with more details here.

Converting JSON to Array

json_decode takes a JSON string and converts it to an array or a stdClass

$jsonString = '{"name": "John Doe", "age": 25, "city": "New York"}';

$stdClass = json_decode($jsonString);

$array = json_decode($jsonString,true);

if we pass true as the second parameter it will return an array and if set it to false or don’t pass it at all, it will return an object of the stdClass.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *