【问题标题】:Using PHP what is the simplest way to check if multiple values are integers?使用 PHP 检查多个值是否为整数的最简单方法是什么?
【发布时间】:2021-12-01 20:04:04
【问题描述】:

我知道可以使用 switch 语句,但我目前有这个来检查所有应该是 int 的函数参数是否显示错误:

if(!is_int($chartWidth)){
   echo "Chart width must be an integer";
}
if(!is_int($chartHeight)){
    echo "Chart height must be an integer";
}
if(!is_int($gridTop)){
    echo "Grid top must be an integer";
}
if(!is_int($gridLeft)){
    echo "Grid left must be an integer";
}

这可以更有效或更短地编码吗?

【问题讨论】:

  • 没有办法。
  • 为什么不直接将它们转换为(int) 并让用户处理生成的任何0 值?

标签: php


【解决方案1】:

如果这些是你所说的函​​数参数,那么从 PHP 5 开始你就可以对函数使用类型提示了。假设您每次可以执行以下操作时都期望一个值。

function chart(int $width, int $height, int $top, int $left) {
    // Some code
}

如果传递给函数的值不是整数类型,则会出现致命错误。

【讨论】:

  • 错误取决于declare(strict_types)
  • @u_mulder 准确地说是as of php8,无论 strict_types 选项如何,传递非法类型的参数都会导致 TypeError。
  • @berend - PHP 仍会为您强制执行 foo('1')foo(1.5) 之类的内容,除非您对分页脚本使用严格类型。
  • 标量类型提示和返回类型声明直到 PHP 7 才可用。
  • @MHewison 我认为这是最好的选择,因为它实现了我的意图,它没有添加额外的代码,为什么我没有想到它大声笑不幸的是,我似乎忘记了我没有运行PHP 8 尚未 :-( 所以我的代码将不得不等待 8。
【解决方案2】:

你可以使用一个函数:

function assertInt($value, $name)
{
    echo is_int($value) ? '' : $name . ' must be an integer.<br>';
}

assertInt($chartWidth,  'Chart width');
assertInt($chartHeight, 'Chart height');
assertInt($gridTop,     'Grid top');
assertInt($gridLeft,    'Grid left');

我不喜欢函数内部的回声,如果你有多个不是整数的变量怎么办?因此,我在末尾添加了&lt;br&gt;

【讨论】:

    【解决方案3】:

    可以使用动态变量名。

    $chartWidth = 100;
    $chartHeight = 200;
    $gridTop = '1,2';
    $gridLeft = 1.2;
    
    $arr = [
      'chartWidth' => "Chart width must be an integer",
      'chartHeight' => "Chart width must be an integer",
      'gridTop' => 'Grid top must be an integer',
      'gridLeft' => 'Grid left must be an integer'
    ];
    
    $result = [];
    foreach($arr as $k => $v) {
        if(!is_int(${$k})){
            $result[] = $v;
        }
    }
    
    print_r($result);
    

    输出

    Array
    (
        [0] => Grid top must be an intege
        [1] => Grid left must be an integer
    )
    

    【讨论】:

      【解决方案4】:

      这将迭代每个变量,如果您想在迭代其余变量之前停止或打印某些内容,我认为这将是最好的

       $data = array($chartWidth,$chartHeight,$gridTop,$gridLeft);
          
          foreach ($data as $value) {
              echo gettype($value) , "\n";
            if(gettype($value)!="integer"){
               // do something
             }
          }
      
      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2011-01-09
      • 1970-01-01
      • 2013-12-03
      • 2015-07-08
      • 2019-05-22
      • 2012-08-25
      相关资源
      最近更新 更多