Oihana PHP

toPhpString.php

Table of Contents

Functions

toPhpString()  : string
Converts any PHP value into a valid PHP code string representation.
convert()  : string
Recursively converts any PHP value into a PHP code string representation.
convertObject()  : string
Converts an object to a PHP string representation with customizable formatting.
convertArray()  : string
Converts an associative or sequential PHP array into a human-readable PHP string representation.

Functions

toPhpString()

Converts any PHP value into a valid PHP code string representation.

toPhpString(mixed $value[, array{compact?: bool, humanReadable?: bool, inline?: bool, indent?: string|int, maxDepth?: int, quote?: "single"|"double", useBrackets?: bool} $options = [] ]) : string
Parameters
$value : mixed

The value to convert.

$options : array{compact?: bool, humanReadable?: bool, inline?: bool, indent?: string|int, maxDepth?: int, quote?: "single"|"double", useBrackets?: bool} = []

Formatting options:

  • 'compact' => (bool) Escape control chars even in single-quote (default: false)
  • 'humanReadable' => (bool) Human-friendly formatting for scalars (default: false)
  • 'inline' => (bool) Single-line output (default: false)
  • 'indent' => (string) Indentation string per level (default: ' ')
  • 'maxDepth' => (int) Max recursion depth (default: 10)
  • 'quote' => ('single'|'double') Quote style for strings (default: 'single')
  • 'useBrackets' => (bool) Use brackets for arrays (default: false)
Tags
example

Example 1: Basic scalar values

echo toPhpString(42);       // '42'
echo toPhpString('hello'); // '\'hello\''
echo toPhpString(true);    // 'true'
echo toPhpString(null);    // 'null'

Example 2: Flat array with short syntax

echo toPhpString(['a' => 1, 'b' => 2], ['useBrackets' => true]);
// Output: ['a' => 1, 'b' => 2]

Example 3: Nested object and array, inline

$data =
[
    'user' =>
    [
        'name' => 'Alice',
        'roles' => ['admin', 'editor'],
        'profile' => (object)['active' => true, 'age' => 30]
    ]
];
echo toPhpString($data, ['useBrackets' => true]);
// Output: ['user' => ['name' => 'Alice', 'roles' => ['admin', 'editor'], 'profile' => (object)['active' => true, 'age' => 30]]]

Example 4: Multiline formatted with indentation

echo toPhpString( $data ,
[
    'useBrackets' => true,
    'inline' => false,
    'indent' => 2
]);
// Output:
// [
//   'user' => [
//     'name' => 'Alice',
//     'roles' => [
//       'admin',
//       'editor'
//     ],
//     'profile' => (object)[
//       'active' => true,
//       'age' => 30
//     ]
//   ]
// ]

Example 5: Object with closure and max depth

$obj = new stdClass();
$obj->callback = fn() => null;
$obj->deep = ['level1' => ['level2' => ['level3' => ['level4' => $obj]]]];

echo toPhpString($obj, ['maxDepth' => 3, 'useBrackets' => true]);
// Output includes: '<max-depth-reached>', '<closure>'

### Example 6: Use double quotes and a human readable rendering
```php
$data =
[
   'message' => "Hello\nWorld",
   'count'   => 1.0,
   'active'  => true
];

echo toPhpString( $data,
[
   'useBrackets'   => true,
   'humanReadable' => true,
   'quote'         => 'double'
]);

// Output
// [
//     'message' => "Hello\nWorld",
//     'count'   => 1,
//     'active'  => true
// ]
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
string

The PHP code string representing the variable.

convert()

Recursively converts any PHP value into a PHP code string representation.

convert(mixed $value, array<string|int, mixed> $options, int $level, array<string|int, mixed> &$cache) : string

Supports scalars, arrays, objects, and resources with options for formatting, indentation, recursion depth control, and human-readable scalar output. Handles circular references to prevent infinite loops.

Parameters
$value : mixed

The value to convert (scalar, array, object, resource, etc.).

$options : array<string|int, mixed>

Formatting options, including:

  • 'maxDepth' (int) Maximum recursion depth allowed.
  • 'indent' (string) Indentation string (default 4 spaces).
  • 'inline' (bool) Whether to output inline (no line breaks).
  • 'useBrackets' (bool) Use short array syntax [] instead of array().
  • 'quote' (string) Quote style for strings ('single' or 'double').
  • 'compact' (bool) Compact output for strings (no extra spaces).
  • 'humanReadable' (bool) Whether to use simplified scalar formatting.
$level : int

Current recursion depth level (used internally).

$cache : array<string|int, mixed>

Internal cache to track visited objects/arrays for circular reference detection.

Tags
example
$data = [
    'name' => "Oihana",
    'count' => 42,
    'active' => true,
    'nested' => ['a', 'b', 'c']
];

echo convert($data, ['maxDepth' => 3, 'indent' => '  ', 'inline' => false, 'useBrackets' => true, 'quote' => 'single', 'compact' => false, 'humanReadable' => true], 0, []);

// Output:
// [
//   'name' => 'Oihana',
//   'count' => 42,
//   'active' => true,
//   'nested' => [
//     'a',
//     'b',
//     'c',
//   ],
// ]
Return values
string

PHP code string representing the given value.

convertObject()

Converts an object to a PHP string representation with customizable formatting.

convertObject(object $obj, array<string|int, mixed> $options, int $level, array<string|int, mixed> &$cache) : string

Supports detection of circular references to prevent infinite recursion. Handles special cases for DateTimeInterface, backed enums (PHP 8.1+), and Closures. For generic objects, converts public properties recursively with indentation and formatting options.

Parameters
$obj : object

The object to convert.

$options : array<string|int, mixed>

Formatting options including:

  • 'maxDepth' (int) Maximum recursion depth allowed.
  • 'indent' (string) Indentation string (default 4 spaces).
  • 'inline' (bool) Whether to output inline (no line breaks).
  • 'useBrackets' (bool) Use short array syntax [] instead of array().
  • 'quote' (string) Quote style for strings ('single' or 'double').
  • 'compact' (bool) Compact output for strings (no extra spaces).
$level : int

Current recursion depth level.

$cache : array<string|int, mixed>

Internal cache to track visited objects for circular reference detection.

Tags
example
$dt = new DateTimeImmutable('2023-08-04T10:30:00+00:00');
echo convertObject($dt, ['maxDepth' => 3, 'indent' => '  ', 'inline' => false, 'useBrackets' => true, 'quote' => 'single', 'compact' => false], 0, []);

// Output:
// new \DateTimeImmutable('2023-08-04T10:30:00+00:00')
since
1.0.0
author

Marc Alcaraz

Return values
string

PHP code string representing the object.

convertArray()

Converts an associative or sequential PHP array into a human-readable PHP string representation.

convertArray(array<string|int, mixed> $array, array<string|int, mixed> $options, int $level, array<string|int, mixed> &$cache) : string

This function is typically used as part of a recursive serialization process to represent array structures in a PHP-style syntax. It supports pretty-printing, inline formatting, bracketed or classic array() syntax, and limits recursion via the maxDepth option.

The output is intended for debugging, code generation, or inspection tools.

Parameters
$array : array<string|int, mixed>

The array to convert.

$options : array<string|int, mixed>

An associative array of formatting options:

  • 'indent' (string): The indentation string (e.g., ' ').
  • 'inline' (bool): If true, output the array on a single line.
  • 'useBrackets' (bool): If true, use [] instead of array().
  • 'maxDepth' (int): The maximum recursion depth.
$level : int

The current depth level in the recursion (used for indentation).

$cache : array<string|int, mixed>

A reference to a cache array used for detecting circular references.

Tags
example
$array = [
    'name' => 'Alice',
    'age'  => 30,
    'tags' => ['developer', 'php'],
];

echo convertArray( $array ,
[
    'indent'      => '  ',
    'inline'      => false,
    'useBrackets' => true,
    'maxDepth'    => 3,
], 0, $cache = []);

// Output:
// [
//   'name' => 'Alice',
//   'age' => 30,
//   'tags' => [
//     'developer',
//     'php'
//   ]
// ]
see
convert()

For the recursive value conversion used within this function.

since
1.0.0
since
1.0.0
Return values
string

The PHP-like string representation of the array.


        
On this page

Search results