【问题标题】:php array numbers comparisonphp数组数字比较
【发布时间】:2018-06-06 22:59:17
【问题描述】:

假设我有

$input = ['1, 2, 3, 4, 5']; 

我需要获取数组中存储为字符串的每个数字。是否有任何可能的方法可以为该字符串中的每个数字使用 foreach() 或其他任何东西?换句话说,从字符串中检索数字。 提前致谢!

【问题讨论】:

  • 循环并在值上运行 is_string() ?

标签: php arrays numbers


【解决方案1】:

使用explode() 将字符串拆分为数字。

foreach ($input as $numberstring) {
    $numbers = explode(', ', $numberstring);
    foreach ($numbers as $number) {
        ...
    }
}

【讨论】:

    【解决方案2】:

    我已经更改了输入数组,因为引号在问题的术语中没有意义,如果这是错误的,请告诉我。

    $input = [1, 2, 3, '4', 5];
    
    
    foreach($input as $i){
    
        if(is_string($i)){//test if its a string
            $strings[]=$i; //put stings in array (you could do what you like here
        }
    
    }
    print_r($strings); 
    

    输出:

    Array
    (
        [0] => 4
    )
    

    您的输入是一个包含一串逗号分隔数字的数组元素

    $input = ['1, 2, 3, 4, 5'];
    

    【讨论】:

      【解决方案3】:

      对于您的示例数据,您可以循环数组并使用is_string 检查数组中的项目是否为字符串。在您的示例中,数字由逗号分隔,因此您可以使用 explode 并使用逗号作为分隔符。

      然后你可以使用is_numeric 来检查explode 的值。

      $input = ['1, 2, 3, 4, 5', 'test', 3, '100, a, test'];
      foreach ($input as $item) {
          if (is_string($item)) {
              foreach (explode(',', $item) as $i) {
                  if (is_numeric($i)) {
                      echo trim($i) . "<br>";
                  }
              }
          }
      }
      

      Demo

      这将导致:

      1
      2
      3
      4
      5
      100
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多