PHP code example of overthink / array-item

1. Go to this page and download the library: Download overthink/array-item library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

overthink / array-item example snippets


use Overthink\ArrayItem\ArrayItem;

$item = ArrayItem::make([
    'name' => 'Widget',
    'price' => '1.234,56',
    'created_at' => '10.10.2020',
    'meta' => ['color' => 'red'],
]);

$item->get('name');                 // 'Widget'
$item->get('missing', 'default');   // 'default'
$item->getOr('missing', fn () => 'computed'); // 'computed'
$item->has('meta.color');           // true

$item->string('name');              // Illuminate\Support\Stringable
$item->float('price');              // 1234.56
$item->number('price')->currency(); // '€1,234.56'
$item->numberFormat('price');       // '1234,56'
$item->collect('meta');             // Illuminate\Support\Collection

$item->date('created_at');                  // Carbon\Carbon
$item->dateFormat('created_at', 'Y-m-d');    // '2020-10-10'
$item->timestamp('created_at');              // Carbon\Carbon (unix timestamp input)

$item->set('meta.size', 'M');
$item->merge(fn ($item) => ['extra' => true]);
$item->only(['name', 'price']);
$item->remove('meta');

$item['name'];                       // ArrayAccess is supported too
$item->toArray();
$item->toCollection();
$item->toJson();

$item = ArrayItem::make(['name' => 'Widget', 'stock' => 0])
    ->when($item->get('stock') === 0, fn (ArrayItem $item) => $item->set('status', 'out_of_stock'))
    ->unless($item->has('sku'), fn (ArrayItem $item) => $item->set('sku', 'N/A'));

use Overthink\ArrayItem\ArrayItem;

ArrayItem::macro('isOutOfStock', function () {
    /** @var ArrayItem $this */
    return $this->get('stock') === 0;
});

$item->isOutOfStock(); // bool

ArrayItem::$dateFormat = 'd.m.Y';
ArrayItem::$decimals = 2;
ArrayItem::$decimalSeparator = ',';
ArrayItem::$thousandsSeparator = '';

$item->number('price')->format();       // '1,234.56'
$item->number('price')->currency();     // '€1,234.56' (defaults to EUR)
$item->number('price')->percentage();
$item->number('price')->abbreviate();
$item->number('price')->spell();        // 

use Overthink\ArrayItem\Convertable;

class UppercaseConverter implements Convertable
{
    public function convert(mixed $value): mixed
    {
        return mb_strtoupper($value);
    }
}

$item->convert('name', new UppercaseConverter()); // 'WIDGET'
bash
php artisan vendor:publish --tag="array-item-config"