PHP 数组数字比较



假设我有

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

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

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

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

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

$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'];

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

然后,您可以使用is_numeric来检查爆炸的值。

$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>";
}
}
}
}

演示

这将导致:

1
2
3
4
5
100