我有这样的foreach循环
foreach($destinations as $destination)
{
if($destination=="abc")
{
$msg = "Yes";
}
else
{
$msg = "No";
}
}
如何计算“foreach 循环”之外的“if 语句”生成的“是”和“否”的数量?
我有这样的foreach循环
foreach($destinations as $destination)
{
if($destination=="abc")
{
$msg = "Yes";
}
else
{
$msg = "No";
}
}
如何计算“foreach 循环”之外的“if 语句”生成的“是”和“否”的数量?
尝试:
$yes = 0;
$no = 0;
foreach($destinations as $destination)
{
if($destination=="abc")
{
$yes += 1;
}
else
{
$no += 1;
}
}
echo "Yes " . $yes . "<br>" . "No " . $no;
在'if'语句中你可以试试这个
$yesCount = 0;
$noCount = 0;
foreach($destinations as $destination)
{
if($destination=="abc")
{
$yesCount++;
$msg = "Yes";
}
else
{
$noCount++;
$msg = "No";
}
}
但我不确定它是否可以在外面使用。
创建两个标志变量并尝试这个
$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;
$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;
只需尝试以下示例:
<?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);
?>
使用 array_count_values() 函数,那么根本不需要循环。
array_count_values($destinations);