PHP code example of madison-solutions / coerce

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

    

madison-solutions / coerce example snippets


use MadisonSolutions\Coerce\Coerce;

if (! Coerce::toInt($_POST['age'] ?? null, $age)) {
    die("Age must be an integer");
}
// $age is definitely now an integer, but might be negative
if ($age < 0) {
    die("Age must be positive");
}
echo "The user is {$age} years old";

use MadisonSolutions\Coerce\Coerce;

$sql = "SELECT option_value FROM options WHERE option_name = 'show_vat_on_prices'";
$show_vat = Coerce::toBoolOrFail($db->get_first_value($sql));
// $show_vat is definitely a boolean, otherwise an exception would have been thrown
if ($show_vat) {
    $price = $price * 1.2;
}
...

// saving the value back to the database
$sql = "UPDATE options SET option_value = ? WHERE option_name = 'show_vat_on_prices'";
$db->update($sql, Coerce::toStringOrFail($show_vat));
// The value send to the database was definitely a string representation of the boolean $show_vat flag - either 'true' or 'false'