Skip to content
← Back to Snippets
Code

Check if a Number is Even or Odd

Checks whether an integer is even or odd using modulo after validating numeric input and returning a structured result.

Purpose

Checks whether an integer is even or odd using modulo after validating numeric input and returning a structured result.

Snippet details

ContextUtilityLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

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.
 */

/**
 * Check if a Number is Even or Odd.
 *
 * Purpose:
 * Validates a submitted value as an integer and classifies it with the modulo
 * operator.
 *
 * @param mixed $value Value to classify.
 * @return array Validation status and even/odd classification.
 */
function ogSnippetCheckIfNumberIsEvenOrOdd($value): array {
	if (is_int($value)) {
		$number = $value;
	} elseif (is_string($value) && preg_match('/^-?[0-9]+$/', trim($value)) === 1) {
		$number = (int) trim($value);
	} else {
		return array(
			'success' => false,
			'number' => null,
			'classification' => 'invalid',
			'message' => 'Value must be an integer.'
		);
	}

	$classification = 'odd';
	if ($number % 2 === 0) {
		$classification = 'even';
	}

	return array(
		'success' => true,
		'number' => $number,
		'classification' => $classification,
		'message' => 'Number classified as '.$classification.'.'
	);
}

$deck_numbers = array('42', '17', '1701', 'not-a-deck');

foreach ($deck_numbers as $deck_number) {
	$result = ogSnippetCheckIfNumberIsEvenOrOdd($deck_number);
	print_r($result);
}