【问题标题】:How do i calculate characters in string without if conditions?如何在没有 if 条件的情况下计算字符串中的字符?
【发布时间】:2017-12-14 23:27:40
【问题描述】:

我有代码示例:

$str = '123456789101112131415';
  if(strlen($str) <9 )
  {
  echo "the string is  10";
  }
  elseif(strlen($str) > 9) {
  echo 'the string is  11';
  }
  elseif(strlen($str) > 21) {
  echo 'the string is  30';
  }
  elseif(strlen($str) > 31) {
  echo 'the string is  40';
  }

我的问题是当字符串很大并且没有在if条件中指定时,我该如何整理

【问题讨论】:

  • echo 'the string is ' . strlen($str);
  • echo 'the string is ' . (strlen($str) - strlen($str)%10)
  • @miknik 不是这个谢谢,我只想在 9 之后
  • 你应该使用数学。

标签: php string if-statement count strlen


【解决方案1】:

计算它!

  1. 致电strlen()
  2. 除以10
  3. 致电floor() 删除小数
  4. 乘以10
  5. 检查是否小于10

这是一系列测试:

代码:(Demo)

$strings=[9=>'123456789',10=>'1234567890',11=>'12345678901',19=>'1234567890123456789',20=>'12345678901234567890',21=>'123456789012345678901'];
foreach($strings as $k=>$str){
    if(($group=floor(strlen($str)/10)*10)<10){  // use arithmetic to find the group, declare and check group in one step
        echo "$k => $str is not upto 10";
    }else{
        echo "$k => $str is in group $group";
    }
    echo "\n";
}

输出:

9 => 123456789 is not upto 10
10 => 1234567890 is in group 10
11 => 12345678901 is in group 10
19 => 1234567890123456789 is in group 10
20 => 12345678901234567890 is in group 20
21 => 123456789012345678901 is in group 20

OP 更新后:

代码:(Demo)

$strings=[9=>'123456789',10=>'1234567890',11=>'12345678901',19=>'1234567890123456789',20=>'12345678901234567890',21=>'123456789012345678901'];
foreach($strings as $k=>$str){
    echo "$k => $str is in group ",(floor(strlen($str)/10)+1)*10,"\n";
}

输出:

9 => 123456789 is in group 10
10 => 1234567890 is in group 20
11 => 12345678901 is in group 20
19 => 1234567890123456789 is in group 20
20 => 12345678901234567890 is in group 30
21 => 123456789012345678901 is in group 30

这是另一种完全符合 OP 要求的方法,但我敢打赌它也“不正确”。

http://sandbox.onlinephpfunctions.com/code/77effe7f68c389bafb1d104a49b7055873e7b038

【讨论】:

  • 很抱歉,我真的不知道如何解释我的问题,但我只想说 if(strlen($str) > 9) { echo 'the string is about 20'; } elseif(strlen($str) > 19) { echo '字符串快 30';只是当字符串比预期的大时,我还能做到这一点吗?
  • 请更新您的问题以准确指定您希望我提供的测试用例的输出。你甚至可以参考我的演示链接。当我更好地了解您的要求时,我可以更新我的答案。
  • 您的问题更新意味着永远不会有10 组。那是你要的吗?您希望upto 组“未满 20 岁”吗?
  • 你想要这个:sandbox.onlinephpfunctions.com/code/… 吗?
  • 我不想在组中我只想在字符串示例中的每个 9 个其他字符之后获取下一个奇数 9 next 20 next 30 next 40
猜你喜欢
  • 1970-01-01
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
  • 2017-06-04
  • 2018-12-26
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多