Viewed   71 times

What is the simplest most basic way to find out if a number/variable is odd or even in PHP? Is it something to do with mod?

I've tried a few scripts but.. google isn't delivering at the moment.



You were right in thinking mod was a good place to start. Here is an expression which will return true if $number is even, false if odd:

$number % 2 == 0

Works for every integerPHP value, see as well Arithmetic OperatorsPHP.


$number = 20;
if ($number % 2 == 0) {
  print "It's even";


It's even

Monday, November 28, 2022

You can use the strcspn function:

if (strcspn($_REQUEST['q'], '0123456789') != strlen($_REQUEST['q']))
  echo "true";
  echo "false";

strcspn returns the length of the part that does not contain any integers. We compare that with the string length, and if they differ, then there must have been an integer.

There is no need to invoke the regular expression engine for this.

Friday, December 9, 2022

They should just roll over:


$var1 = "TEST";


echo $var1; //Outputs TEST
Friday, August 5, 2022
set /a num=%random% %%100 +1
SET /a nummod2=num %% 2
IF %nummod2% == 0 (ECHO %num% is even) ELSE (ECHO %num% is odd)


Conventional IF syntax is if [not] operand1==operand2 somethingtodo where operand1 and operand2 are both strings. If the strings contain separators like Space,Tab or other characters that have a special meaning to batch then the string must be "enclosed in quotes".

Fundamentally, if compares strings. The operator must be one of a fixed set of operators [== equ neq gtr geq lss leq] hence cmd was objecting to num where it expected an operator.

A calculation cannot be performed within a if statement's parameters.

%% is required to perform the mod operation, since % is a special character that itself needs to be escaped by a %.

Note that { and } are ordinary characters with no special meaning to batch and remarks must follow

rem remark string

There is a commonly-used exploit which is


actually, a broken label, which can have unforeseen side-effects (like ending a code-block)

Thursday, November 24, 2022

Use the modulus operator

if(intellect % 2 == 0)
  alert ('is even');
  alert('is odd');
Tuesday, October 11, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :