The print_r output you are seeing is a nested PHP array structure, not a flat list. To foreach it correctly, match your loop depth to the array depth: use a single foreach for one-level arrays, nested foreach loops for multi-dimensional arrays, and key-value syntax (foreach ($arr as $key => $value)) when you need both the index and the data. If the printed output shows Array ( => Array ( [id] => 1 ... ) ), you must loop the outer array first, then loop each inner array to reach the fields you want to echo in the view page.

What print_r Is Actually Showing You

print_r renders a PHP variable in a human-readable form. When the variable is an array, the output uses a bracket-and-arrow notation: keys sit inside square brackets and values follow the => token. A flat array looks like Array ( => apple => banana ). A nested array looks like Array ( => Array ( [name] => apple ) ), where the outer key points to an inner array instead of a scalar.

That visual nesting is the entire source of the confusion. The print_r output is a map of your data's shape. Read the indentation and the Array ( tokens to count how many levels exist before you reach a plain string or number. Each Array ( you open is one loop level you must traverse.

The reason this trips people up is that print_r is a debugging tool, not a data structure. It tells you the shape but does not hand you the keys in code. You still need to know whether the outer array is a list (sequential integer keys) or a map (string keys), and whether the inner values are scalars, objects, or more arrays. The function that answers this precisely is var_dump, which prints types and lengths; use it when print_r leaves you guessing whether a value is the string "1" or the integer 1.

One plain-language way to hold this: print_r is a photograph of your array. A foreach loop is how you walk through the rooms in that photograph, one room at a time, and one shelf at a time inside each room.

How foreach Traverses Nested Structures

foreach in PHP iterates the top level of whatever you hand it. On a one-dimensional array it visits each element once. On a two-dimensional array it visits each inner array once — and hands you that whole inner array as the value, which is why echoing it directly prints the word "Array" instead of your data. This behavior is deliberate and documented in the PHP manual; foreach never silently flattens.

The mechanism is straightforward once you see it: foreach asks the array for its internal pointer, moves it element by element, and assigns the current value to your loop variable. When that current value is itself an array, your loop variable becomes an array. The fix is not a special function. The fix is a second foreach inside the first, pointed at the inner array.

Key-value form matters here. Writing foreach ($rows as $row) gives you only values. Writing foreach ($rows as $index => $row) gives you the key and the value, which you need when the outer array is keyed by something meaningful — an ID, a date, or a category name. For a typical database result set, the outer keys are usually 0, 1, 2 and carry no meaning, so the value-only form is enough at the top level.

The pattern generalizes to any depth. Count the Array ( openings, then write that many nested foreach loops, innermost loop echoing your scalar fields. Two levels of nesting is the common case for query results and decoded JSON. Three levels appears with grouped data. Beyond three, flatten or restructure rather than nesting deeper.

Matching Loop Depth to Array Depth

The table below maps the print_r shape you likely saw to the loop you need. Read the left column against your actual output.

print_r output shape Array depth Loop pattern What goes in the view
=> apple 1 One foreach, value only Echo $value
=> Array ( [name] => apple ) 2 Outer foreach, inner foreach Echo $item['name']
[user] => Array ( [id] => 7 ) 2, string outer key Outer foreach with key, inner foreach Echo $key and $item['id']
=> Array ( => Array ( [name] => apple ) ) 3 Three nested foreaches Echo the innermost scalar
=> stdClass Object ( [name] => apple ) 1 array + objects One foreach, then arrow syntax Echo $obj->name
=> Array ( [tags] => Array ( => red ) ) Mixed Outer foreach, then inner foreach on tags Echo $tag

Two rules resolve most of the table. First, $item['key'] is for arrays; $item->key is for objects. Mixing them throws a fatal error or a notice and returns null. Second, a value that prints as the word "Array" is an array you have not looped yet. That single signal tells you another foreach is required.

When your data comes from json_decode without the second argument set to true, you get objects, not arrays. That is why some developers see stdClass Object in print_r and the array syntax fails. Pass true as the second argument to get associative arrays back, or switch to arrow syntax. Pick one convention and keep it consistent across the view.

Timeline: How a Mangled Loop Usually Unfolds

Debugging these loops follows a predictable sequence. The timeline is not a time course in the clinical sense; it is the order of failures developers hit.

Stage What you observe Underlying cause Correct response
1 print_r shows nested arrays Data is two or more levels deep Count the Array ( openings
2 Single foreach echoes "Array" Loop variable holds an inner array Add a nested foreach
3 Nested loop prints correct fields Depth now matches Move echo statements into inner loop
4 "Undefined index" warning Wrong key name or wrong level Dump one inner element to confirm keys
5 "Trying to get property of non-object" Object data accessed with array syntax Use arrow syntax or decode to arrays
6 Output renders but layout breaks Echo inside loop, HTML outside Restructure markup around the loop

Most people stall at stage 2 because the word "Array" looks like a valid output. It is not. It is PHP telling you the value is composite. Treat any literal "Array" in a rendered page as a red flag that a loop is missing.

Common Misconceptions That Break the View

The most persistent misconception is that print_r returns data you can loop directly. It returns a string. Looping the string iterates characters. To get structured output you loop the original variable, and to capture print_r as text you pass true as the second argument.

A second misconception is that a single foreach handles arrays of any depth. It does not. Foreach is depth-blind: it processes one level and hands you the next level untouched. Deep data requires deep loops, or a recursive function when depth varies.

A third is that count($array) tells you the depth. It tells you the number of top-level elements. A two-element array can be two levels deep; a hundred-element array can be flat. Depth and count are unrelated properties.

For a concrete contrast, consider two developers looking at the same print_r output. One sees => Array ( [id] => 1 [title] => Draft ) and writes two loops, rendering the title correctly. The other writes one loop, echoes the inner array, and ships a page showing the word "Array" next to every record. The data was identical; the loop depth was not. That is the entire failure mode, and it is mechanical, not mysterious.

Red flag: Echoing a variable that prints as "Array" — you are missing a loop level. Red flag: Using $row['field'] when print_r shows stdClass Object — switch to $row->field. Red flag: "Undefined index" after nested loops — you are reading a key from the wrong level. Red flag: json_decode without true and array syntax in the view — decode to associative arrays. Red flag: Loop variables reused across nested loops — inner loops overwrite outer variables.

Practical Actions for the View Page

Follow these steps in order and you will resolve the loop in minutes rather than hours.

Run var_dump($result) once, not print_r. Note the types and the depth. This is the ground truth. If the output shows objects, decide now: decode JSON with true, or use arrow syntax throughout. Do not mix. Write the outermost foreach using key-value syntax only if the keys mean something. Otherwise use value-only. Inside that loop, write a second foreach over the inner array. Echo scalar fields by exact key name copied from var_dump. Keep all echo statements inside the innermost loop that owns those fields. Keep HTML structure outside or between loops. If a field may be absent, guard it with isset() or the null-coalescing operator before echoing. If depth varies, replace nested loops with a recursive function that checks is_array() at each step.

For code clarity, escape output with htmlspecialchars() when rendering user data. For Laravel or similar frameworks, use the template engine's @foreach and @endforeach directives, which follow the same depth rule. The threshold for switching to a recursive helper is roughly three fixed levels; beyond that, flatten the data before it reaches the view.

Limitations and What This Cannot Diagnose

This explanation covers the general mechanism and the common shapes, but it cannot see your actual array. If print_r shows a shape not in the table, the depth-counting method still applies, yet the exact key names must come from your own dump. Data from a database, a JSON API, and a session can share a printed shape while differing in types, so verify with var_dump before writing loops. Output that depends on a specific framework version, template engine, or PHP release should be checked against that system's documentation, because syntax details shift across major versions. Finally, no article can confirm whether your data is valid or safe to render; escaping and validation remain your responsibility in the view layer.