如何计算非空变量以获得非空变量的和



我有表格给出了第六个字段,我只想计算非空


$first = $_POST['first'];
$second = $_POST['second'];
$third = $_POST['third'];
$fourth = $_POST['fourth'];
$fifth = $_POST['fifth'];
$sixth = $_POST['sixth'];

我试着做的是



$count = 0;
if(!empty($first)){ $count = 1;}
else if(!empty($second)) { $count = $count + 1;}
else if(!empty($third)) { $count = $count + 1;}
else if(!empty($fourth)) { $count =$count +  1;}
else if(!empty($fifth)) { $count =$count +  1;}
else if(!empty($sixth)) { $count =$count +  1;}

但不起作用

您还可以使用数组并循环它以获得更好的可读性

$datas = [
'first',
'second',
'third',
'fourth',
'fifth',
'sixth'
];
$sum = 0;
foreach($datas as $data)
if(!empty($_POST[$data])) $sum++;
echo $sum;

如果您想使用您的代码,请删除else并检查每个var,如:

$count = 0;
if(!empty($first)){ $count = 1;}
if(!empty($second)) { $count = $count + 1;}
if(!empty($third)) { $count = $count + 1;}
if(!empty($fourth)) { $count =$count +  1;}
if(!empty($fifth)) { $count =$count +  1;}
if(!empty($sixth)) { $count =$count +  1;}

为什么不直接在var:中检查和求和

$count = 0;
$first = !empty($_POST['first']) ? $_POST['first'] : $count += 1;
$second = !empty($_POST['second']) ? $_POST['second'] : $count += 1;
$third = !empty($_POST['third']) ? $_POST['third'] : $count += 1;
$fourth = !empty($_POST['fourth']) ? $_POST['fourth'] : $count += 1;
$fifth = !empty($_POST['fifth']) ? $_POST['fifth'] : $count += 1;
$sixth = !empty($_POST['sixth']) ? $_POST['sixth'] : $count += 1;
echo $count; // 6 (if all empty)

我使用shortcode来查看var是否为empty,然后使用POST$count + 1

最新更新