Skip to main content

json string ro json array in php

In PHP, use the built-in json_decode() function to convert a JSON string into a PHP array. The key is to pass true as the second argument, which tells the function to return an associative array instead of an object. 

Example: Decoding a JSON object
This example converts a JSON string that represents an object with key-value pairs into an associative PHP array. 
PHP code

php
<?php
// A valid JSON string representing an object
$json_string = '{"name": "Alice", "age": 28, "city": "New York"}';

// Use json_decode() with the second parameter set to true
$php_array = json_decode($json_string, true);

// Output the array using var_dump() for a structured view
var_dump($php_array);

// Access a value from the associative array
echo "Name: " . $php_array['name'];
?>
Use code with caution.
Output

sh
array(3) {
  ["name"]=>
  string(5) "Alice"
  ["age"]=>
  int(28)
  ["city"]=>
  string(9) "New York"
}
Name: Alice
Use code with caution.

Example: Decoding a JSON array
This example converts a JSON string that represents a list of values (a JSON array) into a numerically indexed PHP array. 
PHP code

php
<?php
// A valid JSON string representing an array
$json_array_string = '["apple", "banana", "cherry"]';

// Use json_decode() with the second parameter set to true
$php_array = json_decode($json_array_string, true);

// Output the array using var_dump()
var_dump($php_array);

// Access a value from the indexed array
echo "First fruit: " . $php_array[0];
?>
Use code with caution.
Output

sh
array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(6) "banana"
  [2]=>
  string(6) "cherry"
}
First fruit: apple
Use code with caution.

Important considerations
  • Associative array vs. object: By default, json_decode() returns an object of the stdClass type. Using json_decode($string, true) is the correct way to force it to return an associative array.
  • Invalid JSON: If the JSON string is malformed, json_decode() will return NULL. It's good practice to check for this and use json_last_error() or json_last_error_msg() to get a human-readable error description.
  • Double quotes: The keys and string values in a valid JSON string must be enclosed in double quotes.
  • UTF-8 encoding: json_decode() only works with UTF-8 encoded strings