PHP Array to Json Object

PHP Array to Json Object

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Decoding PHP's JSON Encoding: Arrays vs. Objects

When converting a PHP array to JSON, the resulting structure often depends heavily on how the data is constructed before serialization. The core issue in your scenario isn't a bug in json_encode(), but rather the fundamental difference between how PHP treats indexed arrays and associative arrays, and how the JSON specification maps those types to JavaScript equivalents.

In your current implementation, you are pushing an element into $json using array_push(). This function appends items to the end of a standard array. Because this new element is added at index 0 (or subsequent numeric indices if it were longer), PHP treats the top-level variable as a numeric array. When json_encode() encounters a native PHP array where keys are integers, it serializes them into a JSON array: [...].

To achieve your desired output—a JSON object with a string key like "0" instead of an implicit list—you must explicitly construct the data as an associative array. In PHP, arrays are hash tables that can hold both numeric and string keys. If you define the variable with a string key for the top-level element, json_encode() will respect that structure and output a JSON object {} rather than a JSON array [].

Here is how to modify your code to generate the specific structure you requested:

$json = [];
$ip = "192.168.0.1";
$port = "2016";

// Define the key explicitly as a string "0" instead of relying on array_push
$json["0"] = [
    "ip" => $ip, 
    "port" => $port
];

echo json_encode($json, JSON_PRETTY_PRINT);

This produces:

{
   "0": {
      "ip": "192.168.0.1",
      "port": "2016"
   }
}

Why json_decode Behavior Varies

You mentioned expecting $json["ip"] to return "192.168.0.1" after decoding. This expectation relies on how json_decode() interprets the top-level JSON structure. When you decode a JSON array (e.g., [{...}]), it returns a PHP indexed array. Accessing $json["ip"] on an array will fail because "ip" is a nested key, not a top-level one. You would have to do $json[0]["ip"].

However, when you decode a JSON object (e.g., {"0": {...}}), it returns a PHP associative array. Accessing $json["ip"] will still fail because the top-level key is "0", not "ip". To access the IP address in your target structure, you must use $json["0"]["ip"].

If your goal is to make the data navigable by ip directly (i.e., $json["ip"]), then the JSON object itself should have "ip" as a top-level key. But that contradicts your requirement for a numeric index wrapper. This trade-off between structural hierarchy and direct access paths is common when designing APIs. You must decide if the data represents a collection of items (array) or a single entity with a specific identifier (object).

Practical Considerations in Laravel

In production environments, specifically within the Laravel ecosystem, this distinction becomes critical when handling API responses. If you are returning JSON from a controller using response()->json(), ensure your data collection follows the same pattern. Passing an array of arrays to response()->json() will always yield a JSON array, which is the standard convention for listing resources.

If you specifically need to return a single object where the primary key is numeric (perhaps representing a specific slot or index in a legacy system), you must manually construct that associative array as shown above. However, be aware that relying on string keys like "0" can sometimes confuse clients expecting standard zero-based indexing semantics.

For more robust handling of data structures and automatic model-to-array conversion, Laravel offers toArray() methods on Eloquent models. If you are working with database records, consider mapping those directly to your desired structure within the controller rather than manually building arrays from raw variables. This approach reduces the risk of key mismatches and ensures consistency across your application's data layer.

Ultimately, the behavior is deterministic: PHP preserves the type of its top-level array (numeric vs. associative) during encoding. Adjusting how you initialize or push into that array is the only way to alter the JSON output format.

Our network