### Install YaLinqo using Composer Source: https://context7.com/athari/yalinqo/llms.txt This command installs the YaLinqo library version 3.0 or higher using Composer, the dependency manager for PHP. Ensure Composer is installed and accessible in your environment. ```bash composer require athari/yalinqo ^3.0 ``` -------------------------------- ### Legacy String Lambda Syntax Examples Source: https://github.com/athari/yalinqo/blob/master/readme.md Illustrates various legacy string lambda syntaxes used in older versions of YaLinqo and PHP before arrow functions were standard. These examples show implicit and explicit argument handling, as well as block-based return statements. ```php // Implicit $v and $k arguments, implicit return '"$k = $v"' // Arrow function-like syntax (without fn) '$v ==> $v + 1' // Explicit arguments, implicit return '($v, $k) ==> $v + $k' // Explicit arguments, explicit return within a block '($v, $k) ==> { return $v + $k; }' ``` -------------------------------- ### Install YaLinqo using Composer Source: https://github.com/athari/yalinqo/blob/master/readme.md This snippet shows how to add YaLinqo as a dependency to your PHP project using Composer. It specifies the package name and the desired version constraint. ```json { "require": { "athari/yalinqo": "^3.0" } } ``` -------------------------------- ### Include Composer Autoloader and Use Enumerable in PHP Source: https://github.com/athari/yalinqo/blob/master/readme.md This example demonstrates how to include the Composer autoloader and use the Enumerable class from the YaLinqo library in a PHP script. It shows both static method calls and the global function shortcut for creating an Enumerable instance. ```php require_once 'vendor/autoloader.php'; use \YaLinqo\Enumerable; // 'from' can be called as a static method or via a global function shortcut Enumerable::from([1, 2, 3]); from([1, 2, 3]); ``` -------------------------------- ### Complex Data Processing with YaLinqo in PHP Source: https://context7.com/athari/yalinqo/llms.txt Illustrates a complex data processing pipeline using multiple YaLinqo operations in PHP. This example chains `orderBy`, `groupJoin`, `where`, `orderByDescending`, `thenBy`, `count`, `sum`, and `select` to transform and aggregate product and category data. ```php 'Keyboard', 'catId' => 'hw', 'quantity' => 10, 'price' => 50], ['name' => 'Mouse', 'catId' => 'hw', 'quantity' => 20, 'price' => 25], ['name' => 'Monitor', 'catId' => 'hw', 'quantity' => 0, 'price' => 300], ['name' => 'CPU', 'catId' => 'hw', 'quantity' => 15, 'price' => 200], ['name' => 'Windows', 'catId' => 'sw', 'quantity' => 100, 'price' => 150], ['name' => 'Linux', 'catId' => 'sw', 'quantity' => 50, 'price' => 0], ]; $categories = [ ['name' => 'Hardware', 'id' => 'hw'], ['name' => 'Software', 'id' => 'sw'], ]; // Complex query: Categories with their in-stock products, sorted $result = from($categories) ->orderBy(fn($cat) => $cat['name']) ->groupJoin( from($products) ->where(fn($prod) => $prod['quantity'] > 0) ->orderByDescending(fn($prod) => $prod['quantity']) ->thenBy(fn($prod) => $prod['name'], 'strnatcasecmp'), fn($cat) => $cat['id'], fn($prod) => $prod['catId'], fn($cat, $prods) => [ 'category' => $cat['name'], 'productCount' => $prods->count(), 'totalValue' => $prods->sum(fn($p) => $p['price'] * $p['quantity']), 'products' => $prods->select(fn($p) => [ 'name' => $p['name'], 'quantity' => $p['quantity'], 'value' => $p['price'] * $p['quantity'] ])->toList() ] ) ->toArrayDeep(); print_r($result); /* Output: Array ( [hw] => Array ( [category] => Hardware [productCount] => 3 [totalValue] => 4000 [products] => Array ( [0] => Array ([name] => Mouse, [quantity] => 20, [value] => 500) [1] => Array ([name] => CPU, [quantity] => 15, [value] => 3000) [2] => Array ([name] => Keyboard, [quantity] => 10, [value] => 500) ) ) [sw] => Array ( [category] => Software [productCount] => 2 [totalValue] => 15000 [products] => Array ( [0] => Array ([name] => Windows, [quantity] => 100, [value] => 15000) [1] => Array ([name] => Linux, [quantity] => 50, [value] => 0) ) ) ) */ ?> ``` -------------------------------- ### PHP Pagination Methods: first(), last(), single(), skip(), take(), elementAt() Source: https://context7.com/athari/yalinqo/llms.txt Retrieve specific elements or subsequences from a sequence. `first()` and `last()` get the boundary elements, `single()` retrieves an element that must be unique, and `elementAt()` accesses an element by its index. `skip()` and `take()` are used for slicing sequences, essential for implementing pagination. ```php first(); // 'a' $last = from($items)->last(); // 'e' // With predicate $firstVowel = from($items)->first(fn($v) => in_array($v, ['a', 'e', 'i', 'o', 'u'])); // 'a' // With default value (avoids exception on empty) $missing = from([])->firstOrDefault('default'); // 'default' // Single (expects exactly one match, throws otherwise) $onlyB = from($items)->single(fn($v) => $v === 'b'); // 'b' // Element at key $atIndex2 = from($items)->elementAt(2); // 'c' $atKeyOrDefault = from($items)->elementAtOrDefault(99, 'not found'); // 'not found' // Skip and Take for pagination $page2 = from(range(1, 100)) ->skip(10) // Skip first 10 items ->take(10) // Take next 10 items ->toList(); // Result: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] // SkipWhile and TakeWhile $afterThreshold = from([1, 3, 5, 7, 2, 4, 6]) ->skipWhile(fn($n) => $n < 5) ->toList(); // Result: [5, 7, 2, 4, 6] $untilThreshold = from([1, 3, 5, 7, 2, 4, 6]) ->takeWhile(fn($n) => $n < 5) ->toList(); // Result: [1, 3] ?> ``` -------------------------------- ### Create Enumerable Sequences with YaLinqo `from()` Source: https://context7.com/athari/yalinqo/llms.txt Demonstrates creating an Enumerable sequence from various PHP data structures like arrays, associative arrays, and iterators using the `from()` function or `Enumerable::from()` static method. It also shows how to convert the Enumerable back to an array, preserving keys. ```php ['name' => 'John', 'age' => 30], 'jane' => ['name' => 'Jane', 'age' => 25], ]); // From iterators $iterator = new ArrayIterator([1, 2, 3]); $enumerable = from($iterator); // Convert to array when done $result = from([1, 2, 3, 4, 5]) ->where(fn($v) => $v > 2) ->toArray(); // Result: [2 => 3, 3 => 4, 4 => 5] (keys preserved) ``` -------------------------------- ### Convert Sequences to Arrays and Dictionaries (PHP) Source: https://context7.com/athari/yalinqo/llms.txt Demonstrates how to convert YaLinqo sequences into various array formats like indexed arrays, associative arrays, dictionaries, and lookups. It also shows deep conversion and JSON encoding. ```php 1, 'name' => 'Keyboard', 'category' => 'hw'], ['id' => 2, 'name' => 'Mouse', 'category' => 'hw'], ['id' => 3, 'name' => 'Windows', 'category' => 'sw'], ]; // toArray: preserves keys $arr = from($products)->toArray(); // toList: sequential numeric keys $list = from($products)->toList(); // toArrayDeep: recursively converts nested Enumerables $deep = from($products) ->groupBy(fn($p) => $p['category']) ->toArrayDeep(); // toDictionary: key-value mapping $byId = from($products) ->toDictionary( fn($p) => $p['id'], // key selector fn($p) => $p['name'] // value selector ); // Result: [1 => 'Keyboard', 2 => 'Mouse', 3 => 'Windows'] // toLookup: one-to-many mapping (grouped) $byCategory = from($products) ->toLookup( fn($p) => $p['category'], fn($p) => $p['name'] ); // Result: ['hw' => ['Keyboard', 'Mouse'], 'sw' => ['Windows']] // toJSON: JSON encoding $json = from($products)->toJSON(JSON_PRETTY_PRINT); // toString: join elements $names = from($products) ->select(fn($p) => $p['name']) ->toString(', '); // Result: 'Keyboard, Mouse, Windows' // toKeys/toValues $keys = from(['a' => 1, 'b' => 2])->toKeys()->toList(); // ['a', 'b'] $values = from(['a' => 1, 'b' => 2])->toValues()->toList(); // [1, 2] ``` -------------------------------- ### Group Join with PHP 8.0+ Syntax Source: https://github.com/athari/yalinqo/blob/master/readme.md Demonstrates the groupJoin method with PHP 8.0+ named arguments and PHP 8.1+ first-class callables. It joins categories with products based on IDs, filters products by quantity, orders them, and selects specific fields for the output. The result is then converted to an array. ```php $result = Enumerable::from($categories) ->orderBy(keySelector: fn($cat) => $cat['name']) ->groupJoin( inner: from($products) ->where(predicate: fn($prod) => $prod['quantity'] > 0) ->orderByDescending(keySelector: fn($prod) => $prod['quantity']) ->thenBy(keySelector: fn($prod) => $prod['name'], comparer: strnatcasecmp(...)), outerKeySelector: fn($cat) => $cat['id'], innerKeySelector: fn($prod) => $prod['catId'], resultSelectorValue: fn($cat, $prods) => [ 'name' => $cat['name'], 'products' => $prods ] ); print_r($result->toArrayDeep()); ``` -------------------------------- ### Generate Sequences Programmatically (PHP) Source: https://context7.com/athari/yalinqo/llms.txt Illustrates methods for generating sequences without initial data, including integer ranges, repeated values, custom sequences using a state function, infinite sequences, cycling patterns, and empty or single-element sequences. ```php toList(); // Result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // Range with step $evens = Enumerable::range(2, 5, 2)->toList(); // Result: [2, 4, 6, 8, 10] // RangeDown: descending sequence $countdown = Enumerable::rangeDown(5, 5)->toList(); // Result: [5, 4, 3, 2, 1] // RangeTo: range from start to end $range = Enumerable::rangeTo(1, 5)->toList(); // Result: [1, 2, 3, 4] // Repeat: same value multiple times $fives = Enumerable::repeat(5, 3)->toList(); // Result: [5, 5, 5] // Generate: custom sequence with state function $fibonacci = Enumerable::generate( fn($v, $k) => $v + $k, // value function 1, // seed value fn($v, $k) => $v, // key function (previous value) 1 // seed key )->take(10)->toList(); // Result: Fibonacci-like sequence // ToInfinity: infinite sequence (use with take!) $naturals = Enumerable::toInfinity(1)->take(5)->toList(); // Result: [1, 2, 3, 4, 5] // Cycle: repeat source infinitely $pattern = Enumerable::cycle(['a', 'b', 'c'])->take(7)->toList(); // Result: ['a', 'b', 'c', 'a', 'b', 'c', 'a'] // Empty sequence $empty = Enumerable::emptyEnum()->toList(); // Result: [] // Return single element $single = Enumerable::returnEnum(42)->toList(); // Result: [42] ``` -------------------------------- ### Flatten YaLinqo Sequences with `selectMany()` Source: https://context7.com/athari/yalinqo/llms.txt Demonstrates the `selectMany()` method for flattening sequences. It shows how to project each element to a sequence and combine them into a single sequence, optionally using a result selector to shape the final output with additional context. ```php 'Engineering', 'employees' => ['Alice', 'Bob', 'Charlie']], ['name' => 'Marketing', 'employees' => ['Diana', 'Eve']], ['name' => 'Sales', 'employees' => ['Frank']], ]; // Flatten all employees into a single list $allEmployees = from($departments) ->selectMany(fn($d) => $d['employees']) ->toList(); // Result: ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank'] // With result selector to include department info $employeesWithDept = from($departments) ->selectMany( fn($d) => $d['employees'], // collection selector fn($emp, $deptKey, $empKey) => [ // result value selector 'employee' => $emp, 'department' => $departments[$deptKey]['name'] ] ) ->toList(); // Result: [['employee' => 'Alice', 'department' => 'Engineering'], ...] ``` -------------------------------- ### Combine Sequences (PHP) Source: https://context7.com/athari/yalinqo/llms.txt Explains methods for combining sequences. `concat()` merges two sequences, `append()` adds an element to the end, and `prepend()` adds an element to the beginning. Chaining these operations is also demonstrated. ```php concat($second)->toList(); // Result: [1, 2, 3, 4, 5, 6] // Append: add element to end $extended = from($first)->append(4)->toList(); // Result: [1, 2, 3, 4] // Prepend: add element to beginning $prefixed = from($first)->prepend(0)->toList(); // Result: [0, 1, 2, 3] // Chaining multiple operations $result = from([1, 2, 3]) ->prepend(0) ->append(4) ->concat([5, 6]) ->toList(); // Result: [0, 1, 2, 3, 4, 5, 6] ``` -------------------------------- ### Join Data with join() and groupJoin() in PHP Source: https://context7.com/athari/yalinqo/llms.txt Performs an inner join between two sequences or correlates elements with matching collections. `join()` creates an inner join based on specified key selectors, while `groupJoin()` performs a left outer join. ```php 'hw', 'name' => 'Hardware'], ['id' => 'sw', 'name' => 'Software'], ]; $products = [ ['name' => 'Keyboard', 'catId' => 'hw', 'price' => 50], ['name' => 'Mouse', 'catId' => 'hw', 'price' => 25], ['name' => 'Windows', 'catId' => 'sw', 'price' => 200], ]; // Inner join: products with category names $joined = from($products) ->join( $categories, fn($p) => $p['catId'], // outer key selector (products) fn($c) => $c['id'], // inner key selector (categories) fn($p, $c) => [ // result selector 'product' => $p['name'], 'category' => $c['name'], 'price' => $p['price'] ] ) ->toList(); // Result: [['product' => 'Keyboard', 'category' => 'Hardware', 'price' => 50], ...] // Group join: categories with all their products $grouped = from($categories) ->groupJoin( $products, fn($c) => $c['id'], // outer key (categories) fn($p) => $p['catId'], // inner key (products) fn($c, $prods) => [ 'category' => $c['name'], 'products' => $prods->select(fn($p) => $p['name'])->toList() ] ) ->toList(); // Result: [['category' => 'Hardware', 'products' => ['Keyboard', 'Mouse']], ...] ?> ``` -------------------------------- ### Transform YaLinqo Sequences with `select()` Source: https://context7.com/athari/yalinqo/llms.txt Shows how to use the `select()` method to transform elements within an Enumerable sequence. It covers transforming only values, transforming both values and keys using separate selectors, and extracting a single property from each element. ```php 'John', 'lastName' => 'Doe', 'email' => 'john@example.com'], ['firstName' => 'Jane', 'lastName' => 'Smith', 'email' => 'jane@example.com'], ]; // Transform values only $fullNames = from($users) ->select(fn($u) => $u['firstName'] . ' ' . $u['lastName']) ->toArray(); // Result: [0 => 'John Doe', 1 => 'Jane Smith'] // Transform both values and keys $emailToName = from($users) ->select( fn($u) => $u['firstName'] . ' ' . $u['lastName'], // value selector fn($u) => $u['email'] // key selector ) ->toArray(); // Result: ['john@example.com' => 'John Doe', 'jane@example.com' => 'Jane Smith'] // Extract single property $emails = from($users) ->select(fn($u) => $u['email']) ->toList(); // toList() discards keys // Result: ['john@example.com', 'jane@example.com'] ``` -------------------------------- ### Process and Filter Product Data with YaLinqo Source: https://github.com/athari/yalinqo/blob/master/readme.md This PHP code snippet demonstrates a complex data processing scenario using YaLinqo. It filters products with a quantity greater than zero, sorts them by quantity descending and then by name, and joins them with category data, sorting categories by name. ```php // Data $products = [ [ 'name' => 'Keyboard', 'catId' => 'hw', 'quantity' => 10, 'id' => 1 ], [ 'name' => 'Mouse', 'catId' => 'hw', 'quantity' => 20, 'id' => 2 ], [ 'name' => 'Monitor', 'catId' => 'hw', 'quantity' => 0, 'id' => 3 ], [ 'name' => 'Joystick', 'catId' => 'hw', 'quantity' => 15, 'id' => 4 ], [ 'name' => 'CPU', 'catId' => 'hw', 'quantity' => 15, 'id' => 5 ], [ 'name' => 'Motherboard', 'catId' => 'hw', 'quantity' => 11, 'id' => 6 ], [ 'name' => 'Windows', 'catId' => 'os', 'quantity' => 666, 'id' => 7 ], [ 'name' => 'Linux', 'catId' => 'os', 'quantity' => 666, 'id' => 8 ], [ 'name' => 'Mac', 'catId' => 'os', 'quantity' => 666, 'id' => 9 ], ]; $categories = [ [ 'name' => 'Hardware', 'id' => 'hw' ], [ 'name' => 'Operating systems', 'id' => 'os' ], ]; // Put products with non-zero quantity into matching categories; // sort categories by name; // sort products within categories by quantity descending, then by name. $result = from($categories) ->orderBy(fn($cat) => $cat['name']) ->groupJoin( from($products) ->where(fn($prod) => $prod['quantity'] > 0) ->orderByDescending(fn($prod) => $prod['quantity']) ``` -------------------------------- ### Order Data with orderBy(), orderByDescending(), and thenBy() in PHP Source: https://context7.com/athari/yalinqo/llms.txt Sorts elements by specified keys with support for multiple sort criteria and custom comparers. It takes a collection of data and applies sorting logic based on provided key selectors and optional comparers. ```php 'Keyboard', 'category' => 'hw', 'price' => 50], ['name' => 'Mouse', 'category' => 'hw', 'price' => 25], ['name' => 'Monitor', 'category' => 'hw', 'price' => 300], ['name' => 'Windows', 'category' => 'sw', 'price' => 200], ['name' => 'Linux', 'category' => 'sw', 'price' => 0], ]; // Simple ascending order by price $byPrice = from($products) ->orderBy(fn($p) => $p['price']) ->select(fn($p) => $p['name']) ->toList(); // Result: ['Linux', 'Mouse', 'Keyboard', 'Windows', 'Monitor'] // Descending order $byPriceDesc = from($products) ->orderByDescending(fn($p) => $p['price']) ->select(fn($p) => $p['name']) ->toList(); // Result: ['Monitor', 'Windows', 'Keyboard', 'Mouse', 'Linux'] // Multiple sort criteria: category ascending, then price descending $sorted = from($products) ->orderBy(fn($p) => $p['category']) ->thenByDescending(fn($p) => $p['price']) ->toList(); // Result: hw products (Monitor, Keyboard, Mouse), then sw products (Windows, Linux) // Custom comparer for natural string sorting $names = from(['item10', 'item2', 'item1', 'item20']) ->orderBy(fn($v) => $v, 'strnatcmp') ->toList(); // Result: ['item1', 'item2', 'item10', 'item20'] ?> ``` -------------------------------- ### Group Data with groupBy() in PHP Source: https://context7.com/athari/yalinqo/llms.txt Groups elements by a key, returning a sequence of sequences. It allows for grouping data based on a specified key selector and can also project values and transform the grouped results. ```php 1, 'customer' => 'Alice', 'product' => 'Keyboard', 'amount' => 50], ['id' => 2, 'customer' => 'Bob', 'product' => 'Mouse', 'amount' => 25], ['id' => 3, 'customer' => 'Alice', 'product' => 'Monitor', 'amount' => 300], ['id' => 4, 'customer' => 'Bob', 'product' => 'Headset', 'amount' => 80], ['id' => 5, 'customer' => 'Alice', 'product' => 'Mouse', 'amount' => 25], ]; // Group orders by customer $byCustomer = from($orders) ->groupBy(fn($o) => $o['customer']) ->toArrayDeep(); // Result: ['Alice' => [order1, order3, order5], 'Bob' => [order2, order4]] // Group with value projection $productsByCustomer = from($orders) ->groupBy( fn($o) => $o['customer'], // key selector fn($o) => $o['product'] // value selector ) ->toArrayDeep(); // Result: ['Alice' => ['Keyboard', 'Monitor', 'Mouse'], 'Bob' => ['Mouse', 'Headset']] // Group with result transformation $summaryByCustomer = from($orders) ->groupBy( fn($o) => $o['customer'], fn($o) => $o['amount'], fn($amounts, $customer) => [ // result selector 'customer' => $customer, 'totalOrders' => count($amounts), 'totalAmount' => array_sum($amounts) ] ) ->toList(); // Result: [['customer' => 'Alice', 'totalOrders' => 3, 'totalAmount' => 375], ...] ?> ``` -------------------------------- ### String Operations: Matches and Split (PHP) Source: https://context7.com/athari/yalinqo/llms.txt Provides methods for performing string operations on sequences. `matches()` finds all occurrences of a regex pattern within a string, and `split()` divides a string into parts based on a delimiter regex. ```php select(fn($m) => $m[0]) ->toList(); // Result: ['john@example.com', 'jane@test.org'] // Split: split string by regex $parts = Enumerable::split('one,two;three four', '/[,;\s]+/') ->toList(); // Result: ['one', 'two', 'three', 'four'] ``` -------------------------------- ### Perform Actions on Sequences (PHP) Source: https://context7.com/athari/yalinqo/llms.txt Details methods that perform side effects on sequences. `each()` iterates and executes an action, forcing evaluation. `call()` adds a lazy side effect. `write()` and `writeLine()` output sequence elements to standard output. ```php each(fn($v, $k) => print("$k: $v\n")); // Output: 0: 1, 1: 2, 2: 3, 3: 4, 4: 5 // call: add side effect without forcing evaluation (lazy) $logged = from($items) ->call(fn($v) => error_log("Processing: $v")) ->where(fn($v) => $v > 2) ->toList(); // Logs only happen during toList() evaluation // write: output to stdout from(['Hello', 'World'])->write(' '); // Output: Hello World // writeLine: output with newlines from(['Line 1', 'Line 2', 'Line 3'])->writeLine(); // Output: // Line 1 // Line 2 // Line 3 ``` -------------------------------- ### PHP Quantifier Operations: any(), all(), contains() Source: https://context7.com/athari/yalinqo/llms.txt Test whether elements in a sequence satisfy specified conditions. `any()` checks if at least one element matches a predicate or if the sequence is non-empty. `all()` verifies if all elements meet the condition. `contains()` checks for the presence of a specific value within the sequence. ```php any(fn($n) => $n % 2 === 0); // true $hasOdd = from($numbers)->any(fn($n) => $n % 2 !== 0); // false // Any without predicate: checks if sequence has elements $isEmpty = from([])->any(); // false $hasItems = from([1])->any(); // true // All: checks if all elements match $allEven = from($numbers)->all(fn($n) => $n % 2 === 0); // true $allPositive = from($numbers)->all(fn($n) => $n > 0); // true // Contains: checks for specific value $hasFive = from($numbers)->contains(5); // false $hasSix = from($numbers)->contains(6); // true ?> ``` -------------------------------- ### Type Filtering and Casting with ofType() and cast() in PHP Source: https://context7.com/athari/yalinqo/llms.txt Demonstrates filtering collection elements by type using `ofType()` and converting elements to a specified type using `cast()`. `ofType()` filters based on scalar types or class names, while `cast()` attempts to convert all elements. Both operations are part of the YaLinqo fluent interface. ```php ofType('string')->toList(); // Result: ['hello', 'world'] $integers = from($mixed)->ofType('int')->toList(); // Result: [1, 3] // Filter by class name $objects = [new DateTime(), 'string', new ArrayIterator(), new DateTime()]; $dates = from($objects)->ofType('DateTime')->toList(); // Result: [DateTime, DateTime] // cast: convert all elements to type $numbers = ['1', '2', '3']; $integers = from($numbers)->cast('int')->toList(); // Result: [1, 2, 3] $strings = from([1, 2, 3])->cast('string')->toList(); // Result: ['1', '2', '3'] ?> ``` -------------------------------- ### PHP Aggregation Methods: sum(), average(), min(), max(), count(), aggregate() Source: https://context7.com/athari/yalinqo/llms.txt Compute single values from sequences using accumulator functions or built-in calculations like sum, average, min, max, and count. The `aggregate()` method allows for custom accumulation logic. These methods are useful for summarizing data within a sequence. ```php sum(); // 55 $avg = from($numbers)->average(); // 5.5 $min = from($numbers)->min(); // 1 $max = from($numbers)->max(); // 10 $count = from($numbers)->count(); // 10 // Count with predicate $evenCount = from($numbers)->count(fn($n) => $n % 2 === 0); // 5 // Custom aggregate (factorial) $factorial = from([1, 2, 3, 4, 5]) ->aggregate(fn($acc, $n) => $acc * $n, 1); // Result: 120 // Aggregate with selector $products = [ ['name' => 'A', 'price' => 100, 'qty' => 2], ['name' => 'B', 'price' => 50, 'qty' => 5], ]; $totalValue = from($products)->sum(fn($p) => $p['price'] * $p['qty']); // Result: 450 // Min/Max with selector $cheapest = from($products)->min(fn($p) => $p['price']); // 50 $mostExpensive = from($products)->max(fn($p) => $p['price']); // 100 // MinBy/MaxBy with custom comparer for complex comparisons $longestName = from(['Bob', 'Alice', 'Christopher']) ->maxBy(fn($a, $b) => strlen($a) - strlen($b)); // Result: 'Christopher' ?> ``` -------------------------------- ### Filter YaLinqo Sequences with `where()` Source: https://context7.com/athari/yalinqo/llms.txt Illustrates filtering elements in an Enumerable sequence using the `where()` method with a predicate function. The predicate can access both the value and the key of each element, allowing for conditional selection based on various criteria. ```php 'Keyboard', 'price' => 50, 'inStock' => true], ['name' => 'Mouse', 'price' => 25, 'inStock' => true], ['name' => 'Monitor', 'price' => 300, 'inStock' => false], ['name' => 'Headset', 'price' => 80, 'inStock' => true], ]; // Filter products in stock under $100 $affordable = from($products) ->where(fn($p) => $p['inStock'] && $p['price'] < 100) ->toArray(); // Result: Keyboard, Mouse, Headset // Predicate receives both value and key $indexed = from(['a', 'b', 'c', 'd', 'e']) ->where(fn($v, $k) => $k % 2 === 0) // Even indices only ->toArray(); // Result: [0 => 'a', 2 => 'c', 4 => 'e'] ``` -------------------------------- ### PHP Set Operations: distinct(), union(), intersect(), except() Source: https://context7.com/athari/yalinqo/llms.txt Perform mathematical set operations on sequences. `distinct()` removes duplicates, `union()` combines unique elements from multiple sequences, `intersect()` finds common elements, and `except()` returns elements present in the first sequence but not the second. These are useful for data comparison and merging. ```php distinct() ->toList(); // Result: [1, 2, 3, 4] // Union: combine unique elements $combined = from($set1) ->union($set2) ->toList(); // Result: [1, 2, 3, 4, 5, 6, 7, 8] // Intersect: common elements $common = from($set1) ->intersect($set2) ->toList(); // Result: [4, 5] // Except: elements in first but not in second $difference = from($set1) ->except($set2) ->toList(); // Result: [1, 2, 3] // With key selector for complex objects $users1 = [['id' => 1, 'name' => 'Alice'], ['id' => 2, 'name' => 'Bob']]; $users2 = [['id' => 2, 'name' => 'Bob'], ['id' => 3, 'name' => 'Charlie']]; $uniqueUsers = from($users1) ->union($users2, fn($u) => $u['id']) ->toList(); // Result: users with ids 1, 2, 3 (no duplicates) ?> ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.