PHP表示奇偶数方法

Published
April 19, 2022
浏览次数 :  1

The three ways are

Modulo

for ($i = 0; $i < 10; $i++)
{
  if ($i % 2 == 0)
  {
    echo "even";
  }
  else
  {
    echo "odd";
  }
}

Flipping boolean value

$even = true;
for ($i = 0; $i < 10; $i++)
{
  if ($even)
  {
    echo "even";
  }
  else
  {
    echo "odd";
  }

  $even = !$even;
}

And mentioned boolean operator

for ($i = 0; $i < 10; $i++)
{
  if ($i & 1 == 0)
  {
    echo "even";
  }
  else
  {
    echo "odd";
  }
}

The most fastest is boolean operator. But the most robust is flipping method if you have very different numbers (like running through ID numbers and some are missing).


Top