Installation:
composer require adbario/php-dot-notation
No additional configuration is required—just autoload via Composer.
First Use Case: Access nested array values with dot notation:
use Adbar\Dot;
$array = ['user' => ['name' => 'John', 'details' => ['age' => 30]]];
echo Dot::get($array, 'user.name'); // Output: "John"
echo Dot::get($array, 'user.details.age'); // Output: 30
Where to Look First:
Dot::get(), Dot::set(), and Dot::delete() methods for core functionality.Dot::setDefault() for default value handling.Accessing Nested Data:
$data = ['config' => ['theme' => 'dark', 'notifications' => ['enabled' => true]]];
$theme = Dot::get($data, 'config.theme'); // "dark"
Setting Nested Values:
Dot::set($data, 'config.theme', 'light');
// $data now: ['config' => ['theme' => 'light', ...]]
Deleting Nested Keys:
Dot::delete($data, 'config.notifications');
// Removes the 'notifications' sub-array.
Default Values:
$value = Dot::get($data, 'user.address.city', 'Unknown');
// Returns 'Unknown' if 'user.address.city' doesn't exist.
Array-to-Object Conversion:
$obj = Dot::object($data);
$obj->config->theme; // Access like an object.
$user = User::find(1);
$theme = Dot::get($user->toArray(), 'preferences.theme');
$requestData = json_decode($request->getContent(), true);
$email = Dot::get($requestData, 'user.contact.email');
config('services.stripe.key') alternative).
$stripeKey = Dot::get(config('services'), 'stripe.key');
Overwriting Existing Keys:
Dot::set() will overwrite the entire array if the path doesn’t exist. Use Dot::setDefault() to avoid this:
Dot::setDefault($data, 'new.key', 'value'); // Only sets if 'new.key' is missing.
Case Sensitivity:
Dot notation is case-sensitive. 'User.Name' ≠ 'user.name'.
Non-Array Inputs:
Passing non-array data to Dot::get() will throw an exception. Validate inputs:
if (is_array($data)) {
Dot::get($data, 'path');
}
Performance: Deeply nested operations on large arrays may impact performance. Cache results if reused:
$cached = [];
$cached['theme'] = Dot::get($data, 'config.theme');
Dot::has() to verify a path exists before accessing:
if (Dot::has($data, 'user.profile')) {
Dot::get($data, 'user.profile');
}
null surprises:
Dot::get($data, 'path.to.value', []); // Default to empty array.
Custom Separators:
Override the default . separator by extending the class:
class CustomDot extends Dot {
protected static $separator = '::';
}
Usage:
CustomDot::get($data, 'user::profile');
Validation:
Combine with Laravel’s Validator for nested data:
$validator = Validator::make($data, [
'user.profile.email' => 'required|email',
]);
Array Manipulation: Useful for serializing/deserializing complex data structures (e.g., Redis, caching).
How can I help you explore Laravel packages today?