PHPackages                             apphp/pretty-print - 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. [Logging &amp; Monitoring](/categories/logging)
4. /
5. apphp/pretty-print

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

apphp/pretty-print
==================

Callable pretty-printer for PHP arrays with Python-like formatting.

0.7.0(2mo ago)91231[1 PRs](https://github.com/apphp/pretty-print/pulls)MITPHPPHP &gt;=8.1

Since Nov 22Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/apphp/pretty-print)[ Packagist](https://packagist.org/packages/apphp/pretty-print)[ Docs](https://apphp.com)[ RSS](/packages/apphp-pretty-print/feed)WikiDiscussions main Synced today

READMEChangelog (10)Dependencies (10)Versions (17)Used By (0)

Pretty Pprint
=============

[](#pretty-pprint)

[![GitHub stars](https://camo.githubusercontent.com/55ad0119dbd06a21f60c116d0c898950136fc864e15d675b4026b171c436a53a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f61707068702f7072657474792d7072696e743f7374796c653d736f6369616c)](https://camo.githubusercontent.com/55ad0119dbd06a21f60c116d0c898950136fc864e15d675b4026b171c436a53a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f61707068702f7072657474792d7072696e743f7374796c653d736f6369616c)[![Last commit](https://camo.githubusercontent.com/4832887be1b4b5dfc4a3a3941208c378aebf34d108eca9af36d4c12c78a7ef5f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f61707068702f7072657474792d7072696e74)](https://camo.githubusercontent.com/4832887be1b4b5dfc4a3a3941208c378aebf34d108eca9af36d4c12c78a7ef5f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f61707068702f7072657474792d7072696e74)[![License](https://camo.githubusercontent.com/e5f16c4894781a34cc11108db158dfb4cecb0ce0c62345bd9bef8dad3810e828/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f61707068702f7072657474792d7072696e74)](https://camo.githubusercontent.com/e5f16c4894781a34cc11108db158dfb4cecb0ce0c62345bd9bef8dad3810e828/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f61707068702f7072657474792d7072696e74)[![Link Check](https://github.com/apphp/pretty-print/actions/workflows/php.yml/badge.svg)](https://github.com/apphp/pretty-print/actions/workflows/php.yml/badge.svg)[![Coverage](https://camo.githubusercontent.com/32855e94577df9d0a30995653b17d33a5fbfdf644518f96ea0374313397d19b7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d3130302532352d627269676874677265656e)](https://camo.githubusercontent.com/32855e94577df9d0a30995653b17d33a5fbfdf644518f96ea0374313397d19b7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d3130302532352d627269676874677265656e)

Callable pretty-printer for PHP arrays with Python-like formatting. PrettyPrint is a small, zero-dependency PHP utility that formats arrays in a clean, readable, PyTorch-inspired style. It supports aligned 2D tables, 3D tensors, summarized tensor views, and flexible output options – making it ideal for ML experiments, debugging, logging, and educational projects.

Installation
------------

[](#installation)

```
composer require apphp/pretty-print
```

Usage
-----

[](#usage)

Note: When used in web (non-CLI) environments, output is automatically wrapped in `` to preserve spacing. In CLI, no wrapping is applied. When you request a string to be returned (see `return` option), no auto-wrapping is applied.

### Import functions

[](#import-functions)

All examples below assume you have imported the helper functions from the `Apphp\PrettyPrint` namespace, for example:

```
use function Apphp\PrettyPrint\pprint;
use function Apphp\PrettyPrint\pp;
use function Apphp\PrettyPrint\ppd;
```

or simply

```
use function Apphp\PrettyPrint\{pprint, pp, ppd, pdiff, pcompare};
```

### Global helper functions

[](#global-helper-functions)

Print scalars/strings

```
pprint('Hello', 123, 4.56);
// Hello 123 4.5600
```

Print 1D arrays

```
pprint([1, 23, 456], [12, 3, 45]);
// [1, 23, 456]
// [12, 3, 45]
```

Compare two arrays with a difference matrix

```
$a = [
    [1, 2, 3],
    [4, 5, 6],
];

$b = [
    [1, 9, 3],
    [0, 5, 7],
];

pdiff($a, $b);
// [[1, '-', 3],
//  ['-', 5, '-']]
```

Compare two arrays by printing both matrices (stacked) with colored cells

```
$a = [
    [1, 2, 3],
    [4, 5, 6],
];

$b = [
    [1, 9, 3],
    [0, 5, 7],
];

pcompare($a, $b);
// prints $a above $b
// - equal cells are green
// - different/missing cells are red
// In CLI: ANSI colors; in web:  inside
```

[![pcompare colored output](assets/pcompare-example.svg)](assets/pcompare-example.svg)

Label + 2D matrix

```
pprint([[1, 23], [456, 7]], label: 'Confusion matrix:');
// Confusion matrix:([
//   [  1, 23],
//   [456,  7]
// ])
```

2D tensor-style formatting

```
$matrix = [
    [1,2,3,4,5],
    [6,7,8,9,10],
    [11,12,13,14,15],
];
pprint($matrix);
// array([
//   [ 1,  2,  3,  4,  5],
//   [ 6,  7,  8,  9, 10],
//   [11, 12, 13, 14, 15]
// ])
```

Custom label instead of "tensor"

```
pprint($matrix, label: 'arr');
// arr([
//   [ 1,  2,  3,  4,  5],
//   [ 6,  7,  8,  9, 10],
//   [11, 12, 13, 14, 15]
// ])
```

2D tensor-style formatting with summarization

```
$matrix = [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
    [11, 12, 13, 14, 15],
    [16, 17, 18, 19, 20],
    [21, 22, 23, 24, 25],
];
pprint($matrix, headRows: 2, tailRows: 1, headCols: 2, tailCols: 2);
// array(5x5)([
//   [ 1,  2, ...,  4,  5],
//   [ 6,  7, ...,  9, 10],
//   ...,
//   [21, 22, ..., 24, 25]
// ])
```

3D tensor with head/tail blocks (PyTorch-like)

```
$tensor3d = [
    [[1, 2, 3],[4, 5, 6]],
    [[7, 8, 9],[10, 11, 12]],
    [[13, 14, 15],[16, 17, 18]],
];
pprint($tensor3d, headB: 1, tailB: 1, headRows: 1, tailRows: 1, headCols: 1, tailCols: 1);
// array(3x2x3)([
//  [[1, ..., 3],
//   [4, ..., 6]],
//  ...,
//  [[13, ..., 15],
//   [16, ..., 18]]
// ])
```

Select specific rows/columns

```
$matrix = [
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
    [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22],
    [23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33],
];

// Single row (1-based)
pprint($matrix, rowsOnly: 2);

// Sparse rows and columns: rows 1,2,3,5,6 and cols 1,2,6,9,10
pprint($matrix, rowsOnly: '1-2,3,5-6', colsOnly: '1-2,6,9-10');

// Works the same for 3D tensors (applied per 2D slice)
pprint($tensor3d, rowsOnly: '2-3', colsOnly: '1,3-4');
```

Postfix and prefix control

```
// No newline at the end (like Python's end="")
pprint('Same line', end: '');
// Added newline at the end after printing
pprint('Add line');
pprint('Add line', end: "\n");
// Added addedional 2 newlines at the end after printing
pprint('Add 2 lines', end: "\n\n");

// Add a prefix at the start of the printed string
pprint('Tabbed', start: "\t");
// Combine with end to avoid newline
pprint('Prompted', start: '>>> ', end: '');

// Custom separator between multiple values (default is a single space " ")
pprint('A', 'B', 'C', sep: ', ', end: '');
// A, B, C

// Separator can also be provided via trailing options array
pprint('X', 'Y', sep: "\n", end: '']);
// X
// Y
```

Return the formatted string instead of printing

```
$s = pprint([1, 2, 3], return: true);
// $s contains: "[1, 2, 3]\n" (no  wrapping)
```

Print and then exit the script

```
ppd('Fatal error');
```

### As an object

[](#as-an-object)

```
use Apphp\PrettyPrint\PrettyPrint;

$pp = new PrettyPrint();
$pp('Hello', 42);       // same as pprint('Hello', 42)

$tensor3d = [
    [[1, 2, 3],[4, 5, 6]],
    [[7, 8, 9],[10, 11, 12]],
    [[13, 14, 15],[16, 17, 18]],
];

// Named options are supported
$pp($tensor3d, headB: 2, tailB: 1, headRows: 1, tailRows: 1, headCols: 1, tailCols: 1);

// Label + 2D
$pp('Metrics:', [[0.91, 0.02], [0.03, 0.88]]);
```

### Objects with `asArray()` / `toArray()`

[](#objects-with-asarray--toarray)

If you pass an object that exposes an `asArray()` or `toArray()` method, `pprint` / `PrettyPrint` will automatically convert it to an array before formatting:

```
class Users
{
    public function asArray(): array
    {
        return [
            ['id' => 1, 'name' => 'Alice'],
            ['id' => 2, 'name' => 'Bob'],
        ];
    }
}

$users = new Users();

pprint($users);
// Users([
//   [1, 'Alice'],
//   [2,   'Bob']
// ])
```

If `asArray()` is not present but `toArray()` is, `toArray()` will be used instead.

### Associative rows and strings in arrays/tensors

[](#associative-rows-and-strings-in-arraystensors)

- Associative rows are normalized to positional values in 2D/3D formatting.
- String cells inside arrays/tensors are always printed with quotes (for example, `'engaged'`).
- Top-level scalar strings are unchanged and remain unquoted.

```
$rows = [
    ['distance' => 1.0440, 'label' => 'engaged'],
    ['distance' => 2.2361, 'label' => 'engaged'],
];

pprint($rows);
// array([
//   [1.0440, 'engaged'],
//   [2.2361, 'engaged']
// ])
```

Running tests
-------------

[](#running-tests)

```
# Install dev dependencies
composer install

# Run test suite
composer test

# Run tests with coverage (requires Xdebug or PCOV)
composer test:coverage
```

Notes:

- **Coverage drivers**: You need Xdebug (xdebug.mode=coverage) or PCOV enabled for coverage reports. Without a driver, PHPUnit will warn and exit non‑zero.
- You can also run PHPUnit directly: `vendor/bin/phpunit`.

Benchmark
---------

[](#benchmark)

A CLI benchmark script is available at `benchmarks/benchmark.php` for measuring matrix build/format time and peak memory usage.

Examples:

```
# Default preset (small)
php benchmarks/benchmark.php

# Estimate very large shapes without allocating memory
php benchmarks/benchmark.php --preset=100k --dry-run
php benchmarks/benchmark.php --preset=1m --dry-run

# Custom size with safety cap
php benchmarks/benchmark.php --rows=2000 --cols=2000 --max-cells=5000000
```

Notes:

- Presets: `small`, `10k`, `100k`, `1m`.
- Use `--dry-run` for huge shapes to avoid OOM.
- The script skips materialization if total cells exceed `--max-cells`.

### Options reference

[](#options-reference)

- **start**: string. Prefix printed before the content. Example: `pprint('Hello', ['start' => "\t"])`.
- **end**: string. Line terminator, default is double lines. Example: `pprint('no newline', ['end' => '']);`
- **sep**: string. Separator between multiple default-formatted arguments. Default is a new line. Examples: `pprint('A','B','C', sep: ', ', end: '')` or `pprint('X','Y', ['sep' => "\n", 'end' => ''])`.
- **label**: string. Prefix label for 2D/3D formatted arrays, default `array`. Example: `pprint($m, ['label' => 'arr'])`.
- **precision**: int. Number of digits after the decimal point for floats. Example: `pprint(3.14159, precision: 2)` prints `3.14`.
- **return**: bool. When true, do not echo; return the formatted string instead (no `` wrapping in web context). Example: `$s = pprint($m, return: true);`.
- **headB / tailB**: ints. Number of head/tail 2D blocks shown for 3D tensors.
- **headRows / tailRows**: ints. Rows shown per 2D slice with ellipsis between.
- **headCols / tailCols**: ints. Columns shown per 2D slice with ellipsis between.
- **rowsOnly / colsOnly**: int or string. Limit visible rows/columns.
    - Single index: `3` or `'3'`.
    - Range: `'2-4'` (inclusive).
    - Sparse mix: `'1-2,5,9-11'` → indices `1,2,5,9,10,11`. Applied to 2D arrays and to each 2D slice of 3D tensors.

All options can be passed as:

- trailing array: `pprint($m, ['headRows' => 1, ...])`
- named args (PHP 8+): `$pp($m, headRows: 1, ...)`

#### Defaults

[](#defaults)

- **label**: `tensor`
- **sep**: `' '`
- **precision**: `4`
- **headB / tailB**: `5`
- **headRows / tailRows**: `5`
- **headCols / tailCols**: `5`

#### Limits

[](#limits)

- **precision**: max `10`
- **headB / tailB / headRows / tailRows / headCols / tailCols**: max `50`
- **label**: max length `50` characters (longer labels are truncated)
- **positional args (MAX\_ARGS)**: up to `32` positional args are accepted; extras are ignored.

Positional policy:

- First arg can be a string label, number, or array.
- Exactly two positional args are allowed only for `string label, array`.
- Named/trailing options are applied only when the first arg is an array.

###  Health Score

43

—

FairBetter than 89% of packages

Maintenance91

Actively maintained with recent releases

Popularity20

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

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 ~12 days

Recently: every ~37 days

Total

14

Last Release

61d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/9803e512c3636b0cfa0224e247621e178ad0fe34f399a413be9b63148f636b70?d=identicon)[apphp](/maintainers/apphp)

---

Top Contributors

[![apphp](https://avatars.githubusercontent.com/u/5477692?v=4)](https://github.com/apphp "apphp (133 commits)")

---

Tags

array-formattingdata-formattingmatrix-formatphppretty-printpretty-printerprintertensor-formattingphploggingarraydebugmatrixformattingprinttensordata-formattingpretty-printpprintarray-formattingmatrix-formattensor-formatting

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/apphp-pretty-print/health.svg)

```
[![Health](https://phpackages.com/badges/apphp-pretty-print/health.svg)](https://phpackages.com/packages/apphp-pretty-print)
```

###  Alternatives

[justbetter/magento2-sentry

Magento 2 Logger for Sentry

1861.6M3](/packages/justbetter-magento2-sentry)[phpconsole/phpconsole

A detached logging facility for PHP to aid your daily development routine

417.5k1](/packages/phpconsole-phpconsole)

PHPackages © 2026

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