Display A Tree Natively¶
<?php
$data = [
'src' => [
'Controller' => ['HomeController.php', 'ApiController.php'],
'Entity' => ['User.php', 'Product.php'],
'Kernel.php',
],
'tests' => ['AppTest.php'],
'composer.json',
];
$tree = new RecursiveTreeIterator(
new RecursiveArrayIterator($data)
);
foreach ($tree as $line) {
echo $line . "\n";
}
// Output:
// |-src
// | |-Controller
// | | |-HomeController.php
// | | \-ApiController.php
// | |-Entity
// | | |-User.php
// | | \-Product.php
// | \-Kernel.php
// |-tests
// | \-AppTest.php
// \-composer.json
// (also works with RecursiveDirectoryIterator!)
PHP has a built-in ASCII tree renderer. In the SPL.
RecursiveTreeIterator takes any recursive structure (arrays, directories, XML…) and outputs a formatted indented tree.
tree command behavior. In PHP. Since 5.3.
Pretty sure I would have use it a few times if I knew it existed 😅.
See Also¶
PHP Features¶
Last updated: 14 July 2026