How to Convert Array/Object to JSON in PHP

From WikiHTP

Sometimes you may want to receive an information from PHP through Ajax. Receiving a string as Ajax Response Code is may difficult to read about information. So one of the easiest ways to read information is JSON output so that you have to encode a JSON string in PHP. Here we are going to discuss how to convert array/object to JSON in PHP.

Encoding a JSON string[edit]

The json_encode function will convert a PHP array (or, since PHP 5.4, an object which implements the JsonSerializable interface) to a JSON-encoded string. It returns a JSON-encoded string on success or FALSE on failure.

$array = [
    'name' => 'Jeff',
    'age' => 20,
    'active' => true,
    'colors' => ['red', 'blue'],
    'values' => [0=>'foo', 3=>'bar'],
];

During encoding, the PHP data types string, integer, and boolean are converted to their JSON equivalent. Associative arrays are encoded as JSON objects, and – when called with default arguments – indexed arrays are encoded as JSON arrays. (Unless the array keys are not a continuous numeric sequence starting from 0, in which case the array will be encoded as a JSON object.)

echo json_encode($array);

Output:

{"name":"Jeff","age":20,"active":true,"colors":["red","blue"],"values":{"0":"foo","3":"bar"}}

Related[edit]

About This Tutorial

This page was last edited on 28 January 2019, at 07:34.