PHP code example of aphonix / option

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

    

aphonix / option example snippets




use function Aphonix\Option\{Some, None};

// Wrap a value that exists
$some = Some("Aphonix");

// Represent the absence of a value
$none = None();

if ($some->is_some()) {
    echo $some->unwrap(); // Output: Aphonix
}

$result = Some("  hello world  ")
    ->map('trim')
    ->map('strtoupper')
    ->filter(function ($s) {
        return strlen($s) > 5;
    })
    ->unwrap_or("DEFAULT");

echo $result; // Output: HELLO WORLD

function find_user($id) {
    $users = [1 => ['name' => 'Alice']];
    return isset($users[$id]) ? Some($users[$id]) : None();
}

$name = Some(1)
    ->and_then('find_user')
    ->map(function ($user) { return $user['name']; })
    ->unwrap_or("Unknown");

echo $name; // Output: Alice