Reputation: 342
I have foreach loop like this
foreach($destinations as $destination)
{
if($destination=="abc")
{
$msg = "Yes";
}
else
{
$msg = "No";
}
}
How can I count number of "Yes" and "No" generated by "if statement" outside "foreach loop"?
Upvotes: 0
Views: 711
Reputation: 5108
Inside 'if' statement you can try this
$yesCount = 0;
$noCount = 0;
foreach($destinations as $destination)
{
if($destination=="abc")
{
$yesCount++;
$msg = "Yes";
}
else
{
$noCount++;
$msg = "No";
}
}
But i am not sure whether it can be used outside.
Upvotes: 2
Reputation: 3289
Create two flag variables and try this
$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;
Upvotes: 1
Reputation: 2928
Just try with the following example :
<?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);
?>
Upvotes: 1
Reputation: 526
Use the array_count_values() function, no need for a loop at all then.
array_count_values($destinations);
Upvotes: 0
Reputation: 3084
$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;
Upvotes: 1
Reputation: 5500
Try:
$yes = 0;
$no = 0;
foreach($destinations as $destination)
{
if($destination=="abc")
{
$yes += 1;
}
else
{
$no += 1;
}
}
echo "Yes " . $yes . "<br>" . "No " . $no;
Upvotes: 2