0

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"?

2
  • This question is a joke, right? How can any competent programmer not know how to do this? Commented Jan 8, 2013 at 10:41
  • its not a joke, I'm just tired of coding since morning hence my level of thinking is at its lowest now :D Commented Jan 8, 2013 at 10:47

6 Answers 6

2

Try:

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

echo "Yes " . $yes . "<br>" . "No " . $no;
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

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;

Comments

1

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);
?>

Comments

1

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;

Comments

0

Use the array_count_values() function, no need for a loop at all then.

array_count_values($destinations);

1 Comment

How does that count the number of "abc" elements in $destinations?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.