Display Array as a Table

Display Array as a Table

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

Stefan Bogdanescu

Founder & Senior Architect

Why PHP Outputs First Characters for Single-Row Arrays

When iterating over database results or JSON payloads to render an HTML table, a single edge case can break your layout: having exactly one row in your dataset. You might encounter behavior where print_r confirms your array structure is correct—perhaps containing one associative array with keys like id, first_name, and last_name—but your output displays only the first letter of strings or just the integer value repeated across columns instead of the full data.

This specific issue, often described as "working perfectly when I have 0 items or more than 1," points to a misunderstanding of how PHP renders HTML tags versus how it handles variable content within those tags.

The Root Cause: Tag Parsing Logic

The core misunderstanding in the reported scenario lies in the expectation that the browser will render the exact string sent by the server, regardless of its length. However, when using echo or heredoc syntax inside a loop, PHP simply concatenates strings and outputs them to the buffer. If the resulting HTML structure is valid, the browser renders it correctly.

In the specific example provided where the array contains only one item:

Array ( [id] => 3 [first_name] => Jim [last_name] => Dude )

And the code loops through $result printing each value inside <td> tags, the resulting HTML sent to the browser is:

<table>
  <tr>
    <td>3</td>
    <td>Jim</td>
    <td>Dude</td>
  </tr>
</table>

If the output shows J, D or just 3 repeated, it implies that the HTML parser on the client side (or a proxy like an older browser mode) might be truncating content if it detects certain patterns, though this is rare in modern environments.

A more likely culprit, based on the "first character" symptom described, is how the data itself is being accessed or if there is invisible whitespace handling. However, a much more common scenario that mimics this behavior involves string concatenation precedence or variable scope issues that cause the loop to execute incorrectly, effectively repeating the first iteration's output multiple times if the loop counter logic is flawed.

But let's look at the specific symptom: "1 2 3" on the first row, then "m m m", then "l l l". This pattern suggests that the HTML structure is being interpreted as a single line of text rather than a table grid in some contexts, or the PHP code is inadvertently echoing the raw keys instead of values.

The Associative Array Pitfall

The most frequent technical error causing this exact visual glitch involves how you iterate over an associative array when using foreach. If the loop variable $item is not being accessed correctly, or if the array keys are numeric strings rather than integers, PHP's internal handling can sometimes behave unexpectedly depending on the PHP version.

However, the real issue often stems from how the data is returned. If your backend returns a single associative array directly without wrapping it in an indexed array (e.g., [0] => [...]), and your frontend code expects to iterate multiple times, you must ensure your loop logic handles the singular case gracefully.

Consider this robust pattern for rendering tables dynamically:

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>
        </tr>
    </thead>
    <tbody>
        <?php if (!empty($result)): ?>
            <?php foreach ($result as $row): ?>
                <tr>
                    <td><?= htmlspecialchars($row['id']) ?></td>
                    <td><?= htmlspecialchars($row['first_name']) ?></td>
                    <td><?= htmlspecialchars($row['last_name']) ?></td>
                </tr>
            <?php endforeach; ?>
        <?php else: ?>
            <tr><td colspan="3">No data available</td></tr>
        <?php endif; ?>
    </tbody>
</table>

Notice the use of htmlspecialchars(). While this doesn't fix the "first character" bug directly, it prevents XSS vulnerabilities when echoing user data. The critical part here is the conditional check !empty($result).

Handling the Single-Row Edge Case

The observation that "it works perfectly when I have 2 or more" but fails with "1" usually indicates a logic error in how the loop variable is defined or how the HTML structure is closed. In standard PHP, a foreach loop executes once for one element. If you are seeing repeated content (like m m m), it suggests that the <td> tags might not be closing properly before the next iteration, or the browser is collapsing the whitespace between tags when the content is short.

If your array structure changes from:

[0] => [ ... ]
[1] => [ ... ]

To:

[ ... ] // Single associative array

You must ensure your iteration logic adapts. If $result is a single associative array and not an indexed list of rows, you shouldn't foreach. You should render the row directly:

<?php if (is_array($result) && count($result) === 1): ?>
    <tr>
        <td><?= $result['id'] ?></td>
        <td><?= $result['first_name'] ?></td>
        <td><?= $result['last_name'] ?></td>
    </tr>
<?php elseif (is_array($result)): ?>
    <?php foreach ($result as $row): ?>
        <tr>
            <td><?= $row['id'] ?></td>
            <td><?= $row['first_name'] ?></td>
            <td><?= $row['last_name'] ?></td>
        </tr>
    <?php endforeach; ?>
<?php endif; ?>

This approach explicitly handles the single-item case versus a multi-item list. By checking count($result), you avoid relying on implicit loop behavior that might behave differently based on PHP's internal array hashing or key types (integer vs string keys).

Best Practices for Dynamic Tables

When building dynamic tables in PHP, always separate the table structure from the data population. Define headers statically, then populate <tbody> rows conditionally. This decouples your layout logic from your data retrieval logic.

If you are using Laravel or a similar framework, consider binding this logic to a view component. If the dataset is truly dynamic and might contain zero, one, or many rows, always guard against empty arrays to prevent rendering malformed HTML (e.g., an opening <tbody> tag with no rows, which some strict parsers dislike).

By explicitly checking the array count and handling the single-row case separately or ensuring the loop variable is strictly indexed, you eliminate the ambiguity that causes browsers or older clients to misinterpret the content length. The solution isn't about changing the HTML tags but ensuring the PHP output stream sends a valid, complete set of opening and closing tags for every cell, regardless of how many rows exist in $result.

Our network