Skip to content
← Back to Snippets
Code

Sanitize and Validate an Integer

Validates an integer string with filter_var(), applies an explicit min/max range, and returns either the integer or an error message.

Purpose

Validates an integer string with filter_var(), applies an explicit min/max range, and returns either the integer or an error message.

Snippet details

ContextValidationLevelPracticalCopy-and-paste statusMarked safe after review.

Categories

  • Security

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Sanitize and Validate an Integer.
 *
 * Purpose:
 * Validates an integer and enforces an approved range.
 *
 * @param string $raw_value Raw submitted value.
 * @param int $minimum Minimum accepted value.
 * @param int $maximum Maximum accepted value.
 * @return array Validation result.
 */
function ogSnippetValidateInteger(string $raw_value, int $minimum, int $maximum): array {
	$result = array(
		'valid' => false,
		'value' => 0,
		'message' => 'Integer value is invalid.'
	);

	$raw_value = trim($raw_value);

	if ($raw_value === '') {
		$result['message'] = 'Integer value is required.';
		return $result;
	}

	if ($minimum > $maximum) {
		$result['message'] = 'Integer range is invalid.';
		return $result;
	}

	$options = array(
		'options' => array(
			'min_range' => $minimum,
			'max_range' => $maximum
		)
	);

	$validated = filter_var($raw_value, FILTER_VALIDATE_INT, $options);

	if ($validated === false) {
		return $result;
	}

	$result['valid'] = true;
	$result['value'] = (int) $validated;
	$result['message'] = 'Integer value is valid.';

	return $result;
}

$integer_report = ogSnippetValidateInteger('1701', 1, 9999);

echo 'Registry number: '.$integer_report['value'];