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.

 Answers

1

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.

Example:

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

Output:

It's even

Monday, November 28, 2022
3

You can use the strcspn function:

if (strcspn($_REQUEST['q'], '0123456789') != strlen($_REQUEST['q']))
  echo "true";
else
  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
 
4

They should just roll over:

File1.php

<?php
$var1 = "TEST";
?>

File2.php

<?php
include("File1.php");
echo $var1; //Outputs TEST
?>
Friday, August 5, 2022
 
joetjah
 
2
@ECHO OFF
SETLOCAL
set /a num=%random% %%100 +1
SET /a nummod2=num %% 2
IF %nummod2% == 0 (ECHO %num% is even) ELSE (ECHO %num% is odd)

GOTO :EOF

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

::comment

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

Thursday, November 24, 2022
 
2

Use the modulus operator

if(intellect % 2 == 0)
{
  alert ('is even');
}
else
{
  alert('is odd');
}
Tuesday, October 11, 2022
 
adzzz
 
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 :