1

I have a foreach loop with an if statement inside it so that if $value equals 'Messages' it should increment my variable num1 by 1, but the if statement doesn't appear to be working correctly. Any help would be greatly appreciated.

EDIT: If I get rid of the if statement and just echo $value, it will echo out the value of every section in the array.

Code:

 <?php
     $num1 = 0;
     foreach($inventory['Category'] as $key => $value) {
         if ($value == 'Messages') {  
             $num1++;  
         }
     }
 ?>
7
  • 1
    Try just a var_dump($value == 'Messages') in the loop instead of the if - if it returns false when it should return true there is something wrong in the comparison. You could then try var_dump($value) to narrow down what that variable is returning. Commented Nov 8, 2011 at 18:40
  • Are you sure that $value will contains exactly 'Messages'? I mean, without space or anything else? Do a var_dump to double check. Commented Nov 8, 2011 at 18:40
  • Can you do a var_dump() on `$inventory['Category'] to verify that any values are Messages first? Otherwise the code looks fine. Commented Nov 8, 2011 at 18:41
  • Out of curiosity, what would the key be? Commented Nov 8, 2011 at 18:41
  • 1
    I'm not sure what you're trying to do, but array_count_values might be of use to you. Commented Nov 8, 2011 at 18:44

2 Answers 2

2

The only reason $num1 is not increasing could be because $value is not 'Messages'. Try echoing $value variable & see.

Sign up to request clarification or add additional context in comments.

Comments

0

Are you sure you don't want to do this:

<?php
 $num1 = 0;
 foreach($inventory as $key => $value) {
         if ($value == 'Messages') {  $num1++;  }
 }
 ?>

If you array has a key called $inventory['Messages'] this would find it. Your original sample looks for $inventory['Category']['Messages'].

1 Comment

This will find the value Messages in the array $inventory. This would not find $inventory['Messages'] - In order to do that, it would need to compare $key to 'Messages', not $value. For that reason, the OP's original sample does not look for $inventory['Category']['Messages'].

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.