PHPackages                             calabrothers/php-ds-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. calabrothers/php-ds-tree

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

calabrothers/php-ds-tree
========================

PHP Tree Support

1.0.0(6y ago)20MITPHP

Since Jan 19Pushed 6y ago1 watchersCompare

[ Source](https://github.com/calabrothers/php-ds-tree)[ Packagist](https://packagist.org/packages/calabrothers/php-ds-tree)[ Docs](http://www.calabrothers.com)[ RSS](/packages/calabrothers-php-ds-tree/feed)WikiDiscussions master Synced today

READMEChangelog (1)Dependencies (2)Versions (2)Used By (0)

PHP Tree Support
================

[](#php-tree-support)

[![Build Status](https://camo.githubusercontent.com/7ec3d3847f08c3d02ada8f2b6f5bab6caffd74f12d699e42819f60943fb8cf0c/68747470733a2f2f7472617669732d63692e6f72672f63616c6162726f74686572732f7068702d64732d747265652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/calabrothers/php-ds-tree.svg?branch=master) [![Coverage Status](https://camo.githubusercontent.com/6b5c29176fa5b18ea7c25b5e8cc4359fdb3bce8b671c68cb581fa74d792fd2a6/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f63616c6162726f74686572732f7068702d64732d747265652f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/calabrothers/php-ds-tree?branch=master) [![Total Downloads](https://camo.githubusercontent.com/f04babe662530c2e328084294533352d33aaa7d120e81d469c0f50a5b9075dfe/68747470733a2f2f706f7365722e707567782e6f72672f63616c6162726f74686572732f7068702d64732d747265652f646f776e6c6f616473)](https://packagist.org/packages/calabrothers/php-ds-tree) [![License](https://camo.githubusercontent.com/968f124eb45980549dfb925d963ec1d19ee8c4b25fb5bb0de61bb3a87ce84aba/68747470733a2f2f706f7365722e707567782e6f72672f63616c6162726f74686572732f7068702d64732d747265652f6c6963656e7365)](https://packagist.org/packages/calabrothers/php-ds-tree)

A class to support bitmask operations.

Install
-------

[](#install)

```
composer require calabrothers/php-ds-tree

```

Test
----

[](#test)

```
composer install
composer test

```

Tree Library
------------

[](#tree-library)

Referring to the example tree: [![TreeExampleImg](docs/imgs/tree.svg)](docs/imgs/tree.svg)

We can introduce the following relevant information to discuss library functionality:

SetValueRoot NodeALeaves{H, I, E, F, G}

Relationship with other nodes:

SetValueChildren(A){ B , C }Parent(B)ASiblings(D){ E, F, G }Descendants(B){ D, E, H, I }Anchestors(H){ D, B, A }

For each of this set, an additional set is defined including the argument itself, hence:

SetValueChildrenAndSelf(A){ A, B , C }SiblingsAndSelf(D){ D, E, F, G }DescendantsAndSelf(B){ B, D, E, H, I }AnchestorsAndSelf(H){ D, B, A }

### Static functions:

[](#static-functions)

As Ds\\Deque object, the Tree library provides access to the following operations:

- **apply** (change the value of the node with a callable)
- **filter** (select a subset of nodes where the condition is specified with a a callable)
- **map** (evaluate the nodes value to compute the result given with a callable)

These basic operation are provided as static functions and they operate with a given set of nodes. A magic function provide access to all the previously defined sets.

Example: Let us calculate

```
    y = 2 x sum( Descendants(A) )

```

First we need to get a set of nodes given as Descendants(A), then apply a map to double the value. Finally we should sum the elements of the resulting vector.

```
// Let build some tree...
/*
        A(1)
        /    \
    B(2)   C(3)
            /   \
            D(4)  E(5)

*/
$oA = new TreeNode(1);
$oB = new TreeNode(2);
$oC = new TreeNode(3);
$oD = new TreeNode(4);
$oE = new TreeNode(5);

```

Connect the nodes to form the tree:

```
// Connects the nodes
$oC->attachChild($oD);
$oC->attachChild($oE);
$oA->attachChild($oB);
$oA->attachChild($oC);

```

Compute the result:

```
// Compute 2 x Value, forall the Descendants(A)
$aValue = TreeNode::mapSet(
    $oA->getDescendants(),
    function ($oValue) {
        return 2 * $oValue;
    }
);
echo $aValue->sum()."\n"; // 28

```

Referring to the same tree, we can for example get the list of nodes having even value as:

```
// Get nodes having even value
$aEven = TreeNode::filterSet(
    $oA->getNodes(),
    function ($oValue) {
        return $oValue % 2 == 0;
    }
);

echo "(".$aEven[0]->getValue().",".$aEven[1]->getValue().")"; // (2,4)

```

Tree Builder
------------

[](#tree-builder)

Library provides a convenient class to help construction of trees.

The builder requires a callable, responsible to build new nodes. For example considering a tree of integer values:

```
$oTreeC = new TreeBuilder(
            function (int $nNumber) : int {
                return $nNumber;
            }
        );

```

With this information, everytime the function begin() is called, a new node is added, forwarding the parameters of the begin() function to the callable function specified in the TreeBuilder constructor.

```
$oTreeC
    ->begin(1)
        ->begin(2)
        ->end()
        ->begin(3)
            ->begin(4)
            ->end()
            ->begin(5)
            ->end()
        ->end()
    ->end();

```

It is possible for all the types with a proper \_\_toString() method to see the node values. For instance, in this case:

```
echo $oTree;
// Result:
┌1
└────2
└────3
    └────4
    └────5

```

The TreeBuilder is interesting when combined with custom node class, for example, let us consider to build a Tree having as nodes the object of following class:

```
class TreeNodeExample {
    public $nX;
    public $szY;
    public function __construct(int $nX, string $szY) {
        $this->nX   = $nX;
        $this->szY  = $szY;
    }

    public function myMultiply(int $nZ) {
        $this->nX *= $nZ;
        $this->szY = implode("+", array_fill(0, $nZ,$this->szY));
    }

    public function __toString():string {
        return "($this->nX|$this->szY)";
    }
}

```

Then we can use a TreeBuilder as:

```
$oTreeC = new TreeBuilder(
    function (int $nX, string $szY) : TreeNodeExample {
        return new TreeNodeExample($nX, $szY);
    }
);

$oTreeC
    ->begin(1, 'one')
        ->begin(2, 'two')
        ->end()
        ->begin(3, 'three')
            ->begin(4, 'four')
                ->myMultiply(2)  // This will call the method of TreeNodeExample! :)
            ->end()
            ->begin(5, 'five')
                ->myMultiply(3)
            ->end()
        ->end()
    ->end();

echo $oTreeC;

┌(1|one)
└────(2|two)
└────(3|three)
    └────(8|four+four)
    └────(15|five+five+five)

```

Notes
-----

[](#notes)

I strongly reccomend to use PHP Ds extension rather than its equivalent Php version. Check  for more information.

### Credits

[](#credits)

- [Vincenzo Calabrò](www.cybertronics.cloud/vc)

### Support quality code

[](#support-quality-code)

[![Foo](https://camo.githubusercontent.com/648ad6f048733f167bf65e11a4fd759eef14da88db61ad078bbd5ddea5d57133/68747470733a2f2f7777772e70617970616c6f626a656374732e636f6d2f656e5f55532f692f62746e2f62746e5f646f6e6174655f4c472e676966)](https://paypal.me/muawijhe)

### License

[](#license)

The MIT License (MIT). Please see [LICENSE](LICENSE.md) for more information.

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity3

Limited adoption so far

Community4

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

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

Unknown

Total

1

Last Release

2301d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/11202330?v=4)[muawijhe](/maintainers/muawijhe)[@muawijhe](https://github.com/muawijhe)

---

Tags

librarytreeds

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/calabrothers-php-ds-tree/health.svg)

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

###  Alternatives

[knplabs/knp-menu

An object oriented menu library

1.4k55.8M285](/packages/knplabs-knp-menu)[cuyz/valinor

Dependency free PHP library that helps to map any input into a strongly-typed structure.

1.5k9.2M108](/packages/cuyz-valinor)[league/iso3166

ISO 3166-1 PHP Library

69536.3M116](/packages/league-iso3166)[dekor/php-array-table

PHP Library for printing associative arrays as text table (similar to mysql terminal console)

296.6M2](/packages/dekor-php-array-table)

PHPackages © 2026

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