PHP code example of masterfermin02 / slash

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

    

masterfermin02 / slash example snippets



// Map: Transform each element in an array
slash()->map([1, 2, 3], fn($n) => $n * 2);  // [2, 4, 6]

// Filter: Keep only elements that pass a test
slash()->filter([1, 2, 3, 4, 5], fn($n) => $n % 2 === 0);  // [2, 4]

// Reduce: Combine all elements into a single value
slash()->reduce([1, 2, 3, 4], fn($acc, $n) => $acc + $n, 0);  // 10


// Group data by a property
$records = [
    ["id" => 1, "value1" => 5, "value2" => 10],
    ["id" => 1, "value1" => 1, "value2" => 2],
    ["id" => 2, "value1" => 50, "value2" => 100],
    ["id" => 2, "value1" => 15, "value2" => 20],
    ["id" => 3, "value1" => 15, "value2" => 20]
];

$grouped = slash()->groupBy($records, 'id');
/*
Result:
[
    1 => [
        ["id" => 1, "value1" => 5, "value2" => 10],
        ["id" => 1, "value1" => 1, "value2" => 2]
    ],
    2 => [
        ["id" => 2, "value1" => 50, "value2" => 100],
        ["id" => 2, "value1" => 15, "value2" => 20]
    ],
    3 => [
        ["id" => 3, "value1" => 15, "value2" => 20]
    ]
]
*/


// Find maximum value
slash()->max([1, 2, 3]);  // 3

// Flatten nested arrays
slash()->flatten([1, [2, [3]]]);  // [1, 2, 3]

// Get last elements
slash()->last([1, 2, 3, 4, 5], 2);  // [4, 5]

// Check if all elements satisfy a condition
slash()->all([1, 3, 5], fn($n) => $n % 2 === 1);  // true (all are odd)

// Check if any element satisfies a condition
slash()->any([1, 2, 3], fn($n) => $n > 2);  // true


// Create a pipeline of operations
$processData = slash()->pipeLine(
    slash()->mapWith(fn($x) => $x * 2),
    slash()->filterWith(fn($x) => $x > 5),
    slash()->sortBy(fn($a, $b) => $a - $b)
);

$result = $processData([1, 4, 2, 5]);
// Result: [6, 8, 10]


// Extract and transform properties from objects
$products = [
    (object)['id' => 1, 'name' => 'Laptop', 'price' => 1000],
    (object)['id' => 2, 'name' => 'Phone', 'price' => 500],
    (object)['id' => 3, 'name' => 'Tablet', 'price' => 300],
];

$discountedPrices = slash()->map(
    $products,
    fn($product) => [
        'name' => $product->name,
        'price' => $product->price * 0.9 // 10% discount
    ]
);