简体   繁体   English

PHP计算数组的非空值的数量

[英]PHP count the amount of not empty values of array

I have this array: 我有这个数组:

$auflistung = array ($_POST['jacken'], $_POST['hosen'], $_POST['oberteil'], $_POST['tasche'], $_POST['schuhe'], $_POST['accessoireschmuck1'], $_POST['accessoireschmuck2'], $_POST['accessoireschmuck3'], $_POST['accessoireschmuck4'], $_POST['accessoireschmuck5'], $_POST['accessoireschmuck6']);

It contains eg: 它包含例如:

array(11) {
  [0]=>      string(10) "1288023365"
  [1]=>      string(10) "1246154493"
  [2]=>      string(0) ""
  [3]=>      string(10) "1293143681"
  [4]=>      string(10) "1293143242"
  [5]=>      string(0) ""
  [6]=>      string(0) ""
  [7]=>      string(0) ""
  [8]=>      string(0) ""
  [9]=>      string(0) ""
  [10]=>     string(0) ""
}

Now i need the amount of aviable values. 现在,我需要大量的可用值。 In this case 4 在这种情况下4

I tried: echo count( $auflistung ); 我试过了:echo count($ auflistung); but the result includes allso the empty values, so 11. Any ideas? 但是结果包括所有空值,所以11.有什么想法吗?

Use array_filter to iterate over each value. 使用array_filter迭代每个值。 If you don't provide a callback, any key whose value == false gets removed. 如果不提供回调,则将删除任何值== false的键。 Empty is close enough to false for PHP. 对于PHP,Empty足够接近false。

echo count(array_filter($auflistung));

ZombieHunter has a good point about creating the array from non-empty values. ZombieHunter对于从非空值创建数组非常有帮助。 This is a clean way of doing that. 这是一种干净的方法。

$keys=array(
    'jacken', 
    'hosen', 
    'oberteil', 
    'tasche', 
    'schuhe', 
    'accessoireschmuck1', 
    'accessoireschmuck2', 
    'accessoireschmuck3', 
    'accessoireschmuck4', 
    'accessoireschmuck5', 
);

$auflistung=array();
foreach ($keys as $key){
    if (isset($_POST[$key]) && !empty($_POST[$key])) $auflistung[]=$_POST[$key];
}

echo count($auflistung);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM