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.
<?php
$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);
var_dump($json);
![](https://phpjunior.com/wp-content/uploads/2023/06/image-18-1024x35.png)
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:
–JSON_FORCE_OBJECT
–JSON_NUMERIC_CHECK
–JSON_HEX_AMP
–JSON_NUMERIC_CHECK
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);
echo($json);
look at the result:
![](https://phpjunior.com/wp-content/uploads/2023/06/image-20.png)
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);
echo($json);
![](https://phpjunior.com/wp-content/uploads/2023/06/image-21.png)
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.
![](https://phpjunior.com/wp-content/uploads/2023/06/image-19.png)