PHP code example of samuelludwig / phprelude

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

    

samuelludwig / phprelude example snippets






 declare(strict_types=1); namespace StructTest;
2($n) {
  return $n+2;
}

function ladd2(): Closure {
  return fn($x) => add2($x);
}

$double = fn($n) => $n*2;
$triple = fn($n) => $n*3;

echo p\pipe([
  $triple,
  $double,
  fn($x) => add2($x),
  ladd2(),
])(4); // (4 * 3 * 2) + 2 + 2 ==> 28

 declare(strict_types=1); namespace StructTest;
array like
$a = [ 'pets_name' => 'mark', 'pet_kind' => 'dog' ];
// and I have some function thats expecting the keys to be named differently, like
// "`animal_name`" instead of "`pet_name`" and "`species`" instead of "`pet_kind`",
// and maybe its also expecting the `species` to always be capitalized, I could
// then write

$new_a =
  Enum\extract_values_into_format(
    $a,
    [ 'animal_name' => 'pets_name'
    , 'species' => ['pet_kind', fn($x) => strtoupper($x)]
    ]);

// Et voila, we have our new array
echo $new_a == [ 'animal_name' => 'mark', 'species' => 'DOG' ]; // 1

 declare(strict_types=1); namespace StructTest;
'first' => 'door', 'second' => 'cat', 'third' => 'orange' ];

// We can extract specific values into a list via:
[ $x, $y ] = Enum\extract_values($a, ['third', 'first']);

echo "$x $y"; // "orange door"

 declare(strict_types=1); namespace StructTest;
e can use const to pseudo-namespace our struct without too much hassle
const UserT = __NAMESPACE__ . '\User';
p\defstruct(
    UserT,
    [ 'id' => [['int', 'string'], 0]
    , 'name' => [['string']]
    ]);

$user0 = p\mk(UserT, ['name' => 'John']);
$user1 = p\mk(UserT, ['id' => 1, 'name' => 'Mike']);

echo Json\encode($user0) . "\n"; // {"id":0,"name":"John"}
echo Json\encode($user1) . "\n"; // {"id":1,"name":"Mike"}