PHP code example of adamnicholson / bag

1. Go to this page and download the library: Download adamnicholson/bag 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/ */

    

adamnicholson / bag example snippets


function foo (array $data) {
    if (!isset($data['status']) || !isset($data['data']['foo'])) || $data['status'] !== 'success') {
        return false;
    }
    return $data['data']['foo'];
}

// vs

function bar (array $data) {
    $data = new Bag($data);

    if ($bag->get('status') !== 'success') {
        return false;
    }

    return $bag->get('data.foo');
}

$array = [
    'foo' => 'bar',
    'hello' => 'world',
    'items' => [
        'first' => 'fizz',
        'second' => 'buzz'
    ]
];

$bag = new Adam\Bag\Bag($array);

// Get a value by key
$bag->get('foo'); // string "bar"

// Set some value by key
$bag->set('fizz', 'buzz');

// Return a default value if the key is not set
$bag->get('ziff'); // null
$bag->get('ziff', 'my_default_value'); // string "my_default_value"

// Use dot notation for multidimensional arrays
$bag->get('items.first'); // string "fizz"
$bag->set('items.third', 'foovalue');

// Get the value of an item and then remove it
$bag->pluck('foo'); // string "bar"
$bag->get('foo'); // null

// Get the raw data
$bag->all(); // array

// Empty the data
$bag->flush();

// Or just use it like an array
$bag['foo'] = 'bar';
$bag['foo']; // string "bar"
$bag->get('foo'); // string "bar"