PHP Type Casting
Casting changes a representation; validation decides whether the original input meets a rule. Do the validation first when accepting data from a request or file.
How it works
A cast can discard information. In particular, a conversion that produces an integer does not prove that all source characters described a permitted integer. FILTER_VALIDATE_INT can enforce an integer format and options can bound its range. Test its failure result strictly: zero is a valid result when the chosen range allows it, while false means validation failed. Filter flags and options belong to a specific field contract, not a blanket sanitisation pass.
Run it locally
Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.
php -l casting.php
php casting.phpDownload this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.
Example
<?php
declare(strict_types=1);
$raw = "12";
$days = filter_var($raw, FILTER_VALIDATE_INT, ["options" => ["min_range" => 1, "max_range" => 30]]);
if ($days === false) {
throw new InvalidArgumentException("Days must be between 1 and 30");
}
echo $days, " days\n";
Expected result
12 daysThe accepted value is already an integer produced by validation, so a further cast is unnecessary. A malformed string or a count outside the allowed range reaches the failure branch. This is a local value example; a request handler should also decide the appropriate status and user-facing error response rather than exposing a development stack trace.
Check the official PHP manual for detailed version and API contracts.