计算foreach循环中的条件输出

时间:2013-01-08 10:27:39

标签: php if-statement foreach

我有这样的循环

foreach($destinations as $destination)
{
if($destination=="abc")
{
 $msg = "Yes";
}
else
{
 $msg = "No";
}
}

如何计算“foreach循环”之外的“if语句”生成的“是”和“否”的数量?

6 个答案:

答案 0 :(得分:2)

尝试:

$yes = 0;
$no = 0;
foreach($destinations as $destination)
{
    if($destination=="abc")
    {
        $yes += 1;
    }
    else
    {
        $no += 1;
    }
}

echo "Yes " . $yes . "<br>" . "No " . $no;

答案 1 :(得分:2)

在'if'语句中你可以尝试这个

    $yesCount = 0;
    $noCount = 0;
    foreach($destinations as $destination)
    {
      if($destination=="abc")
      {
        $yesCount++;
        $msg = "Yes";
      }
      else
      {
        $noCount++;
        $msg = "No";
      }

    }

但我不确定它是否可以在外面使用。

答案 2 :(得分:1)

创建两个标志变量并尝试此

$yesFlag=0;
$noFlag=0;
foreach($destinations as $destination)
{
 if($destination=="abc")
 {
  $msg = "Yes";
  $yesFlag++;  
 } 
 else
 {
   $msg = "No";
   $noFlag++;
 }
}
echo "no. of Yes:".yesFlag;
echo "no. of NO:".noFlag;

答案 3 :(得分:1)

$yesCount = 0;
$noCount = 0;
    foreach($destinations as $destination) {
        if($destination=="abc") {
            $msg = "Yes";
            $yesCount = $yesCount + 1;
        }
        else {
            $msg = "No";
            $noCount = $noCount + 1;
        }
    }
echo $yesCoynt . " --- " . $noCount;

答案 4 :(得分:1)

试试以下示例:

<?php
$destinations = array('abc','def','ghi');
foreach($destinations as $destination)
{
if($destination=="abc")
{
 $msg = "Yes";
 $msg_yes_counter[]= "I'm in"; 
}
else
{
 $msg = "No";
 $msg_no_counter[]= "I'm in";
}
}
echo "YES -> My Count is :".count($msg_yes_counter);
echo "NO -> My Count is :".count($msg_no_counter);
?>

答案 5 :(得分:0)

使用array_count_values()函数,根本不需要循环。

array_count_values($destinations);