dongsu2807 2018-08-28 23:01
浏览 61
已采纳

PHP检查值是否是具有共同差异的数字序列的一部分

I'm writing a script that needs to identify every 7th number where the first number of the sequence is 0 (so the sequence is 6, 13, 20, 27, 34, 41, 48, etc.)

Here's what I've got so far (which works in a limited way), but I'd prefer to write a loop so that the values in the sequence don't have to be hardcoded:

<?php

$x = 7;

if ($x === 6 || $x === 13 || $x === 20 || $x === 27 || $x === 34 || $x === 41 || $x === 48) {
    $result = 1;
  } else {
    $result = 0;
}

echo $result;

?>

Thanks in advance for any advice!


Update: Here's my updated script using @robbieaverill 's solution and checking the values against an array. There are many great solutions here, thanks everyone!

<?php

$divisor = 7;
$limit = 500; 

$sequence = array();

for ($i = 0; $i <= $limit; $i++) {
  if (is_int(($i + 1) / $divisor)) {
    $sequence[] = $i;
  }
}

$x = 41;

if (in_array($x, $sequence, true)) {
  $result = 1;
} else {
  $result = 0;
}

echo $result;
?>

The output here is 1, indicating that if the value of $x is 41 it is found within the $sequence array.

  • 写回答

7条回答 默认 最新

  • dqbr37828 2018-08-28 23:06
    关注

    There's probably a bunch of different ways you could do this. If you need to identify numbers that are evenly divisible by 7 (plus one, because you're zero based), you could do something like this:

    $divisor = 7;
    $limit = 100; // when do you want to stop searching?
    
    for ($i = 0; $i <= $limit; $i++) {
        if (is_int(($i + 1) / $divisor)) {
            var_dump($i);
        }
    }
    

    Note that is_int() is checking whether the divided result is a whole number, it'd return false for a decimal/floating point number.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥50 comsol稳态求解器 找不到解,奇异矩阵有1个空方程返回的解不收敛。没有返回所有参数步长;pid控制
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功