Skip to content

PHP array traversing via tokenized paths

License

Notifications You must be signed in to change notification settings

hostinger/travers

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Travers

Travers is a small PHP package meant for easily traversing arrays using tokenized path strings.

$params = [
    'fruits' => [
        'apple' => 1,
        'avocado' => 1.1,
        'banana' => [
            'baby' => 'baby',
            'ice_cream' => true,
            'casual' => false,
        ],
    ],
];

Travers::get('fruits.apple', $params); // 1
Travers::get('fruits.banana.ice_cream', $params); // true
Travers::get('fruits.banana.casual', $params); // false
Travers::get('fruits.apple.red', $params); // null

Installation

composer require hostinger/travers

Documentation

Initializing

The library can be used either by creating the instance for the class or using it statically.

use Hostinger\Travers\Travers;

$data = [
    'path' => 1,
];

$travers = new Travers($data);

$val = $travers->find('path'); // 1
$val = Travers::get('path', $data); // 1

Configuring

Creating an instance of Travers allows setting additional settings:

$shouldThrowException = true;
$customDelimiter = '=';

$travers = new Travers($data, $shouldThrowException); // If a path is not found, will throw exception instead of returning null
$travers = new Travers($data, false, $customDelimiter); // Will separate path branches by the provided delimiter

Setting data

Travers also allows setting data in an array:

$data = [
    'path' => 1,
];

$travers = new Travers($data);

$data = $travers->change('path', 2); // ['path' => 2]
$data = Travers::set('path', 3, $data); // ['path' => 3]

If the path does not exist in the array, it is created:

$data = Travers::set('path.new.trail', 4, $data);

/**
 * $data = [
 *      'path' => [
 *          'new' => [
 *              'trail' => 4,
 *          ],
 *      ],
 * ];
 */

About

PHP array traversing via tokenized paths

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP 100.0%