PHPackages                             nicmart/tree - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. nicmart/tree

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

nicmart/tree
============

A basic but flexible php tree data structure and a fluent tree builder implementation.

0.10.1(5mo ago)57719.3M↓14.4%62[5 issues](https://github.com/nicmart/Tree/issues)20MITPHPPHP ~8.0.0 || ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0CI passing

Since Apr 22Pushed today11 watchersCompare

[ Source](https://github.com/nicmart/Tree)[ Packagist](https://packagist.org/packages/nicmart/tree)[ RSS](/packages/nicmart-tree/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (8)Versions (36)Used By (20)

Tree
====

[](#tree)

[![Integrate](https://github.com/nicmart/Tree/workflows/Integrate/badge.svg?branch=master)](https://github.com/nicmart/Tree/actions)[![Release](https://github.com/nicmart/Tree/workflows/Release/badge.svg?branch=master)](https://github.com/nicmart/Tree/actions)

[![Code Coverage](https://camo.githubusercontent.com/2628d08fcedad1c510bd7e17898a5260b1f6dbeabd9ad83e02b511d2c0a68892/68747470733a2f2f636f6465636f762e696f2f67682f6e69636d6172742f747265652f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/nicmart/tree)[![Type Coverage](https://camo.githubusercontent.com/2d3ec9c7acf716b93341a14e3748408ccc1e8caa8f3e95544fdf078ba3edb704/68747470733a2f2f73686570686572642e6465762f6769746875622f6e69636d6172742f747265652f636f7665726167652e737667)](https://shepherd.dev/github/nicmart/tree)

[![Latest Stable Version](https://camo.githubusercontent.com/32e7fc6064e49f44aea9e7573834211c03f134040c076e63ce577ae8ad2b7250/68747470733a2f2f706f7365722e707567782e6f72672f6e69636d6172742f747265652f762f737461626c65)](https://packagist.org/packages/nicmart/tree)[![Total Downloads](https://camo.githubusercontent.com/3a35c64e1028ef404d820cf4a1216645a12943a443f86c9f237d7f9814656e65/68747470733a2f2f706f7365722e707567782e6f72672f6e69636d6172742f747265652f646f776e6c6f616473)](https://packagist.org/packages/nicmart/tree)[![Monthly Downloads](https://camo.githubusercontent.com/dc67b10649bf2a443779db04928d284813507a34ef2e164020e6c0c520dbb1f5/687474703a2f2f706f7365722e707567782e6f72672f6e69636d6172742f747265652f642f6d6f6e74686c79)](https://packagist.org/packages/nicmart/tree)

In Tree you can find a basic but flexible tree data structure for php together with and an handful Builder class, that enables you to build tree in a fluent way.

The tree data structure
-----------------------

[](#the-tree-data-structure)

The `Tree\Node\NodeInterface` interface abstracts the concept of a tree node. In `Tree` a Node has essentially two things: a set of children (that implements the same `NodeInterface` interface) and a value.

On the other hand, the `Tree\Node\Node` gives a straight implementation for that interface.

### Creating a node

[](#creating-a-node)

```
use Tree\Node\Node;

$node = new Node('foo');
```

### Getting and setting the value of a node

[](#getting-and-setting-the-value-of-a-node)

Each node has a value property, that can be any php value.

```
$node->setValue('my value');
echo $node->getValue(); //Prints 'my value'
```

### Adding one or more children

[](#adding-one-or-more-children)

```
$child1 = new Node('child1');
$child2 = new Node('child2');

$node
    ->addChild($child1)
    ->addChild($child2);
```

### Removing a child

[](#removing-a-child)

```
$node->removeChild($child1);
```

### Getting the array of all children

[](#getting-the-array-of-all-children)

```
$children = $node->getChildren();
```

### Overwriting the children set

[](#overwriting-the-children-set)

```
$node->setChildren([new Node('foo'), new Node('bar')]);
```

### Removing all children

[](#removing-all-children)

```
$node->removeAllChildren();
```

### Getting if the node is a leaf or not

[](#getting-if-the-node-is-a-leaf-or-not)

A leaf is a node with no children.

```
$node->isLeaf();
```

### Getting if the node is a child or not

[](#getting-if-the-node-is-a-child-or-not)

A child is a node that has a parent.

```
$node->isChild();
```

### Getting the parent of a node

[](#getting-the-parent-of-a-node)

Reference to the parent node is automatically managed by child-modifiers methods

```
$root->addChild($node = new Node('child'));
$node->getParent(); // Returns $root
```

### Getting the ancestors of a node

[](#getting-the-ancestors-of-a-node)

```
$root = (new Node('root'))
    ->addChild($child = new Node('child'))
    ->addChild($grandChild = new Node('grandchild'))
;

$grandchild->getAncestors(); // Returns [$root, $child]
```

#### Related Methods

[](#related-methods)

- `getAncestorsAndSelf` retrieves ancestors of a node with the current node included.

### Getting the root of a node

[](#getting-the-root-of-a-node)

```
$root = $node->root();
```

### Getting the neighbors of a node

[](#getting-the-neighbors-of-a-node)

```
$root = (new Node('root'))
    ->addChild($child1 = new Node('child1'))
    ->addChild($child2 = new Node('child2'))
    ->addChild($child3 = new Node('child3'))
;

$child2->getNeighbors(); // Returns [$child1, $child3]
```

#### Related Methods

[](#related-methods-1)

- `getNeighborsAndSelf` retrieves neighbors of current node and the node itself.

### Getting the number of nodes in the tree

[](#getting-the-number-of-nodes-in-the-tree)

```
$node->getSize();
```

### Getting the depth of a node

[](#getting-the-depth-of-a-node)

```
$node->getDepth();
```

### Getting the height of a node

[](#getting-the-height-of-a-node)

```
$node->getHeight();
```

The Builder
-----------

[](#the-builder)

The builder provides a convenient way to build trees. It is provided by the `Builder` class, but you can implement your own builder making an implementation of the `BuilderInterface`class.

### Example

[](#example)

Let's see how to build the following tree, where the nodes label are represents nodes values:

```
       A
      / \
     B   C
        /|\
       D E F
      /|
     G H

```

And here is the code:

```
$builder = new Tree\Builder\NodeBuilder;

$builder
    ->value('A')
    ->leaf('B')
    ->tree('C')
        ->tree('D')
            ->leaf('G')
            ->leaf('H')
            ->end()
        ->leaf('E')
        ->leaf('F')
        ->end()
;

$nodeA = $builder->getNode();
```

The example should be self-explanatory, but here you are a brief description of the methods used above.

### Builder::value($value)

[](#buildervaluevalue)

Set the value of the current node to `$value`

### Builder::leaf($value)

[](#builderleafvalue)

Add to the current node a new child whose value is `$value`.

### Builder::tree($value)

[](#buildertreevalue)

Add to the current node a new child whose value is `$value`, and set the new node as the builder current node.

### Builder::end()

[](#builderend)

Returns to the context the builder was before the call to `tree`method, i.e. make the builder go one level up.

### Builder::getNode()

[](#buildergetnode)

Returns the current node.

Traversing a tree
-----------------

[](#traversing-a-tree)

### Yield

[](#yield)

You can obtain the yield of a tree (i.e. the list of leaves in a pre-order traversal) using the YieldVisitor.

For example, if `$node` is the tree built above, then

```
use Tree\Visitor\YieldVisitor;

$visitor = new YieldVisitor;

$yield = $node->accept($visitor);
// $yield will contain nodes B, G, H, E, F
```

### Pre-order Traversal

[](#pre-order-traversal)

You can walk a tree in pre-order:

```
use Tree\Visitor\PreOrderVisitor;

$visitor = new PreOrderVisitor;

$yield = $node->accept($visitor);
// $yield will contain nodes A, B, C, D, G, H, E, F
```

### Post-order Traversal

[](#post-order-traversal)

You can walk a tree in post-order:

```
use Tree\Visitor\PostOrderVisitor;

$visitor = new PostOrderVisitor;

$yield = $node->accept($visitor);
// $yield will contain nodes B, G, H, D, E, F, C, A
```

Install
-------

[](#install)

Run

```
$ composer require nicmart/tree

```

Tests
=====

[](#tests)

```
phpunit

```

Changelog
---------

[](#changelog)

Please have a look at [`CHANGELOG.md`](CHANGELOG.md).

Contributing
------------

[](#contributing)

Please have a look at [`CONTRIBUTING.md`](.github/CONTRIBUTING.md).

License
-------

[](#license)

This package is licensed using the MIT License.

Please have a look at [`LICENSE.md`](LICENSE.md).

###  Health Score

73

—

ExcellentBetter than 100% of packages

Maintenance87

Actively maintained with recent releases

Popularity70

Solid adoption and visibility

Community39

Small or concentrated contributor base

Maturity82

Battle-tested with a long release history

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~209 days

Recently: every ~223 days

Total

23

Last Release

175d ago

PHP version history (9 changes)v0.1.0PHP &gt;=5.3.3

v0.2.0PHP &gt;=5.4

0.3.0PHP ^5.4 || ^7.0

0.3.1PHP ^7.1 || ^8.0

0.4.0PHP ^7.2 || ^8.0

0.5.0PHP ~8.0.0 || ~8.1.0 || ~8.2.0

0.8.0PHP ~8.0.0 || ~8.1.0 || ~8.2.0 || ~8.3.0

0.9.0PHP ~8.0.0 || ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0

0.10.0PHP ~8.0.0 || ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/8cabc9efd157e2b47aa5aa9830180f5ebd07813cc3e93ff1a9993b2c3d264909?d=identicon)[localheinz](/maintainers/localheinz)

![](https://www.gravatar.com/avatar/3b9800c1ad66a6e11dfbefe00e4fd88472970370f0f8b5c7c1ebd7d45178335f?d=identicon)[nicmart](/maintainers/nicmart)

---

Top Contributors

[![localheinz](https://avatars.githubusercontent.com/u/605483?v=4)](https://github.com/localheinz "localheinz (281 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (256 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (232 commits)")[![nicmart](https://avatars.githubusercontent.com/u/443063?v=4)](https://github.com/nicmart "nicmart (51 commits)")[![pascalbaljet](https://avatars.githubusercontent.com/u/8403149?v=4)](https://github.com/pascalbaljet "pascalbaljet (2 commits)")[![jdeniau](https://avatars.githubusercontent.com/u/1398469?v=4)](https://github.com/jdeniau "jdeniau (2 commits)")[![smoench](https://avatars.githubusercontent.com/u/183530?v=4)](https://github.com/smoench "smoench (1 commits)")[![szepeviktor](https://avatars.githubusercontent.com/u/952007?v=4)](https://github.com/szepeviktor "szepeviktor (1 commits)")[![asalazar-pley](https://avatars.githubusercontent.com/u/8482108?v=4)](https://github.com/asalazar-pley "asalazar-pley (1 commits)")[![VincentLanglet](https://avatars.githubusercontent.com/u/9052536?v=4)](https://github.com/VincentLanglet "VincentLanglet (1 commits)")[![Djuki](https://avatars.githubusercontent.com/u/416411?v=4)](https://github.com/Djuki "Djuki (1 commits)")[![dwightwatson](https://avatars.githubusercontent.com/u/1100408?v=4)](https://github.com/dwightwatson "dwightwatson (1 commits)")[![lord2800](https://avatars.githubusercontent.com/u/715922?v=4)](https://github.com/lord2800 "lord2800 (1 commits)")[![mark-gerarts](https://avatars.githubusercontent.com/u/11940560?v=4)](https://github.com/mark-gerarts "mark-gerarts (1 commits)")[![peter279k](https://avatars.githubusercontent.com/u/9021747?v=4)](https://github.com/peter279k "peter279k (1 commits)")

---

Tags

data-structruesphptree

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/nicmart-tree/health.svg)

```
[![Health](https://phpackages.com/badges/nicmart-tree/health.svg)](https://phpackages.com/packages/nicmart-tree)
```

###  Alternatives

[phpdocumentor/reflection

Reflection library to do Static Analysis for PHP Projects

12521.4M109](/packages/phpdocumentor-reflection)[spatie/array-functions

Some handy array helpers

24561.1k2](/packages/spatie-array-functions)[cekurte/environment

A library to get the values from environment variables and process to php data types

5884.0k7](/packages/cekurte-environment)[forxer/gravatar

A library providing easy gravatar integration.

35202.0k8](/packages/forxer-gravatar)[netgen/layouts-ui

Netgen Layouts user interface

17110.8k2](/packages/netgen-layouts-ui)[ebidtech/collection

A set of interfaces and traits to speed up the creation of collections

13119.8k6](/packages/ebidtech-collection)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
