PHP code example of selvinortiz / collective

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

    

selvinortiz / collective example snippets


// 1. Create a new instance of Collective
// 2. Give it an (optional) input array
// 3. Call methods on it
$input = ['name' => 'Collective', 'release' => 'alpha'];

(new Collective($input))->get('name');
// 'Collective'

$input = [
    'user' => [
        'name'   => 'Brad',
        'salary' => '100000'
    ]
];

(new Collective($input))->get('users.name');
// 'Brad'

(new Collection())->set('user.name', 'Matt')->toArray();
// ['user' => ['name' => 'Matt']]

$input = [0, 1, 2, 3, 4, 5];

(new Collective($input))->count();
// 6

$input      = [128, 256, 512, 'Brad', 'Brandon', 'Matt'];
$collective = new Collective($input);

$collective->first();
// 128

$collective->first(function($value)
{
    return strpos($value, 'Bra') !== false;
});
// Brad

$input      = [128, 256, 512 'Brad', 'Brandon', 'Matt'];
$collective = new Collective($input);

$collective->last();
// 'Matt'

$collective->last(function($value)
{
    return strpos($value, 'Bra') !== false;
});
// Brandon

$input = [128, 256, 512 'Brad', 'Brandon', 'Matt'];

(new Collective($input))->map(function($value)
{
    return is_string($value) ? '- '.$value : $value;
})->toArray();
// 128, 256, 512, '- Brad', '- Brandon', '- Matt'

$input = [128, 256, 512 'Brad', 'Brandon', 'Matt'];
(new Collective($input))->filter(function($value)
{
    return is_numeric($value);
})->toArray();
// 128, 256, 512

$input    = [
    ['name' => 'Brad', 'salary' => 100000, 'type' => 'yearly'],
    ['name' => 'Brandon', 'salary' => 250000, 'type' => 'yearly']
];

$callback = function ($value, $carry) {
    return $carry + $value['salary'];
};

(new Collective($input))->reduce($callback);
// 350000

(new Collective([128, 256, 512]))->reverse()->toArray();
// [512, 256, 128]

$input = [
    'level1' => [
        'name'   => 'Level 1',
        'level2' => [
            'name'   => 'Level 2',
            'level3' => [
                'name' => 'Level 3'
            ]
        ]
    ]
];

(new Collective($input))->flatten()->toArray();
// ['Level 1', 'Level 2', 'Level 3']

function filterToStrings($collective) {
    return $collective->filter(function ($value) { return is_string($value); });
}

function fourCharsOnly($collective) {
    return $collective->filter(function ($value) { return strlen($value) == 4; });
}

$collective->then('filterToStrings')->then('filterToLength')->toArray();
// 'Brad', 'Matt'