0

我有这样的foreach循环

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

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

4

6 回答 6

2

尝试:

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

echo "Yes " . $yes . "<br>" . "No " . $no;
于 2013-01-08T10:29:41.923 回答
2

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

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

    }

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

于 2013-01-08T10:30:23.037 回答
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;
于 2013-01-08T10:31:48.113 回答
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;
于 2013-01-08T10:31:57.553 回答
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);
?>
于 2013-01-08T10:34:17.327 回答
0

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

array_count_values($destinations);
于 2013-01-08T10:33:36.287 回答