Validation

PHP Input Validation Snippets

Validation helpers for positive integers, allowlisted values and email addresses.

Overview

Validation helpers for positive integers, allowlisted values and email addresses.

Code example

<?php
declare(strict_types=1);
function positiveInt(mixed $v): ?int { $n=filter_var($v,FILTER_VALIDATE_INT); return $n!==false&&$n>0?$n:null; }
function allowedValue(string $v,array $allowed): ?string { return in_array($v,$allowed,true)?$v:null; }
function validEmail(string $v): bool { return filter_var(trim($v),FILTER_VALIDATE_EMAIL)!==false; }

How to use it

Place the snippet in a namespaced helper or service file, adapt its inputs to your application and add tests for expected and edge-case behavior.

Notes

The example is intentionally small. Validate untrusted input, handle exceptions and document any PHP extension or database requirements.