PHP code example of petrobolos / fixed-array-functions

1. Go to this page and download the library: Download petrobolos/fixed-array-functions 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/ */

    

petrobolos / fixed-array-functions example snippets


use Petrobolos\FixedArray\FixedArrayable;

// Create using various methods
$array = new FixedArrayable([1, 2, 3]);
$array = fixedArray([1, 2, 3]);  // Helper function
$array = FixedArrayable::fromCollection(collect([1, 2, 3]));

// Chain methods just like Laravel Collections
$result = fixedArray([1, 2, 3, 4, 5, 6])
    ->filter(fn ($value) => $value % 2 === 0)
    ->map(fn ($value) => $value * 2)
    ->sum();  // Returns 24 (2*2 + 4*2 + 6*2)

use Petrobolos\FixedArray\FixedArray;

$arr = FixedArray::fromArray([1, 2, 3, 4, 5]);

// Aggregate functions
$sum = FixedArray::sum($arr);           // 15
$avg = FixedArray::avg($arr);           // 3
$min = FixedArray::min($arr);           // 1
$max = FixedArray::max($arr);           // 5

// Higher-order functions
$doubled = FixedArray::map($arr, fn($v) => $v * 2);
$evens = FixedArray::filter($arr, fn($v) => $v % 2 === 0);

// Conditional operations
$result = FixedArray::when(
    $arr,
    fn($a) => FixedArray::count($a) > 3,
    fn($a) => FixedArray::push($a, 6)
);

// Efficiently process 100,000 records
$data = FixedArray::create(100000);

for ($i = 0; $i < 100000; $i++) {
    FixedArray::offsetSet($data, $i, fetchRecordFromDatabase($i));
}

$processed = fixedArray($data)
    ->filter(fn($record) => $record->isActive)
    ->map(fn($record) => $record->transform())
    ->toCollection(); // Convert back to Collection for further Laravel operations

$orders = fixedArray($orderArray)
    ->pluck('total')
    ->sum();

$averageAge = fixedArray($users)
    ->avg('age');

$oldestUser = fixedArray($users)
    ->max('created_at');

$processed = fixedArray($items)
    ->when(
        $shouldFilter,
        fn($arr) => $arr->filter(fn($item) => $item->isValid())
    )
    ->unless(
        $skipSorting,
        fn($arr) => $arr->sort()
    )
    ->tap(fn($arr) => logger()->info('Processed items', ['count' => $arr->count()]))
    ->toArray();

[$valid, $invalid] = fixedArray($records)
    ->partition(fn($record) => $record->validate())
    ->toArray();

// $valid contains all validated records
// $invalid contains all failed records