Javascript json_encode > JSON.parse() array

Javascript json_encode > JSON.parse() array

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

Stefan Bogdanescu

Founder & Senior Architect

The JSON Type Mismatch: Why json_encode Breaks Array Iteration in JavaScript

A common stumbling block when bridging PHP and client-side JavaScript involves a subtle type mismatch that manifests as a silent logic failure. Consider a scenario where you are rendering a list of items via an <img> tag, and you need to pass the underlying data object directly into a handler function. The PHP code looks straightforward:

echo '<img src="../images/edit.png" onclick="showEditDiv(' . json_encode($row) . ');">';

When this renders in the browser, the HTML is technically valid. If $row contains properties like ID, NAME, and EMAIL, the resulting onclick attribute becomes a string containing a JSON object: {"ID":"2","NAME":"John Smith"...}. This appears correct at first glance. The function signature expects an argument, and the HTML passes one.

However, the JavaScript logic inside showEditDiv often trips over this expectation. A developer might write:

function showEditDiv(data) {
  alert(data); 
  // ...
  for (i=0; i< data.length; i++){ 
    alert(data[i]);
  };
}

The first alert correctly displays [object Object]. This confirms that the function received a value, but it is an object, not an array. The subsequent loop fails immediately because plain JavaScript objects do not have a numeric .length property accessible in this manner, nor do they support iteration via a standard numeric index starting at zero. Consequently, the loop condition i < data.length evaluates to false instantly (since data.length is undefined or 0), and the alerts inside the loop never fire.

The core issue stems from a fundamental distinction between PHP arrays and JavaScript objects. In PHP, json_encode() treats standard indexed arrays as such, but when you pass an associative array (like $row with named keys like ID and NAME), it serializes them into a JSON object. JavaScript's JSON.parse() then converts that string back into a native JavaScript object. While objects are useful for key-value pairs, they do not support the .length property or numeric indexing required by standard loops.

To iterate over the data as an array, the PHP source must provide an actual JSON array structure, such as [{"ID": "2"}, {"ID": "3"}], rather than a single object. If your intention is to pass a single record object and then process its properties, you should not attempt to iterate using for loops based on length. Instead, you must iterate over the object's keys or use Object.entries():

function showEditDiv(data) {
  console.log(data); 
  for (const key in data) {
    if (data.hasOwnProperty(key)) {
      console.log(`${key}: ${data[key]}`);
    }
  }
}

Alternatively, if the requirement is strictly to pass an array of records and you are iterating over multiple rows, your PHP code needs to wrap the variable in brackets before encoding: json_encode([$row]). This forces PHP to output a JSON array [{"ID":"2",...}], which JavaScript can then iterate using the standard for loop syntax.

Another critical detail involves how data is passed from inline event handlers to external scripts. Passing complex objects directly via onclick="..." strings creates parsing overhead and security risks if not handled carefully, though modern browsers generally handle simple JSON literals safely. A more robust pattern in a separate .js file would be to attach the data to the DOM element itself:

document.addEventListener('DOMContentLoaded', function() {
  const img = document.querySelector('img');
  img.setAttribute('data-row', JSON.stringify({ ID: 2, NAME: 'John' }));
  
  img.onclick = function() {
    const row = JSON.parse(this.getAttribute('data-row'));
    console.log(row);
    // Process single object safely without length-based loops
  };
});

This approach decouples the data transfer from the inline HTML attribute, allowing you to load your logic in a separate file. It also ensures that row is treated as an object with specific keys, requiring iteration methods suitable for objects rather than arrays. Always verify whether the PHP variable represents a collection or a single record; conflating these two concepts leads directly to the [object Object] trap described above.

Our network