0

I apologise if the question was already answered but i didn't find any answer.

In C# i have a basic 'foreach loop' on a Dictionary

foreach(var item in _dict)
{        
   if(item.Key == "test")
   {
      item.Value++; // This line will add one more number to the integer 1+1
   }
}

What's the equivalent code in PHP?

PHP

foreach($Clients as $cl)
{
   if($cl["ChannelID"] == $chanID)
   {
      $cl['Clients']++;
   }
}

However, in C# the append is succesful in the dictionary, but in the PHP array is not, the initial value remains unchanged even if the code was succesful run.

Sorry for my quite noobie question but i don't use PHP much, only asp.net with C#

user3280998
  • 81
  • 1
  • 7
  • See this question on [Increasing array elements while in a `foreach` loop](http://stackoverflow.com/a/22653826/1189566) where this answer states: "Foreach copies structure of array before looping, so you cannot change structure of array and wait for new elements inside loop. You could use `while` instead of `foreach`." Also I don't do PHP but I think you want `$Clients++`, as that's the field you've defined in your `foreach` statement. – sab669 Nov 30 '15 at 15:26
  • 1
    Your C# code could just be `if(_dict.ContainsKey("test")) _dict["test"}++;` since there can only be at most one entry in the dictionary with that key. – juharr Nov 30 '15 at 15:27

2 Answers2

3

You must tell PHP to use $cl as a referenced variable using & before it,

foreach($Clients as &$cl)
{
   if($cl["ChannelID"] == $chanID)
   {
     $cl['Clients']++;
   }
}
MiDri
  • 747
  • 3
  • 13
  • Works! Thanks very much sir. Didn't knew about the "&" symbol. Thanks! – user3280998 Nov 30 '15 at 15:29
  • 2
    @user3280998 If you want more info on the `&` symbol, read [here for References](http://cz2.php.net/manual/en/language.references.php) and [here for `foreach`](http://cz2.php.net/manual/en/control-structures.foreach.php) important quote: "In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference." – sab669 Nov 30 '15 at 15:30
0

How about this one ?

foreach($Clients as $cl)
    {
       if($cl["ChannelID"] == $chanID)
       {
         $id = (int)$cl['Clients'];
         $id =  $id++;
         echo $id; // added just for test 
       }
    }
Aniruddha Chakraborty
  • 1,849
  • 1
  • 20
  • 32