PHP code example of prvious / result

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

    

prvious / result example snippets




declare(strict_types=1);

use Prvious\Result\Result;

/**
 * @return Result<float, string>
 */
function divide(float $dividend, float $divisor): Result
{
    if ($divisor === 0.0) {
        return Result::err('Cannot divide by zero.');
    }

    return Result::ok($dividend / $divisor);
}

$output = divide(10, 2)->match(
    ok: fn (float $value): string => "Result: {$value}",
    err: fn (string $error): string => "...",
);

$ok = Result::ok('created');
$err = Result::err('Email is already registered.');

if ($result->isOk()) {
    $value = $result->unwrap();
}

if ($result->isErr()) {
    $error = $result->error();
}

$result = divide(10, 2)->map(
    fn (float $value): string => number_format($value, 2),
);

$result = divide(10, 0)->mapError(
    fn (string $error): array => ['message' => $error],
);

$result = divide(100, 5)
    ->andThen(
        fn (float $value): Result => divide($value, 2),
    );