Philip
Philip

Reputation: 7166

Replace value in array doesn't work

I'm going crazy, spent a couple of hours trying different methods in replace values in arrays, but I can't get it to work.

foreach($potentialMatches as $potentialKey)
{
  $searchKeywordQuery = "SELECT keyword, id FROM picture WHERE id='$potentialKey'";
  $searchKeywords = mysql_query($searchKeywordQuery) or die(mysql_error());
  while ($searchKeyWordsRow = mysql_fetch_array($searchKeywords))
  {
    $keyword = $searchKeyWordsRow['keyword'];
    $pictureKeywordArray[$searchKeyWordsRow['id']]['keywords'] = explode(",", $keyword);
    $pictureKeywordArray[$searchKeyWordsRow['id']]['match'] = 4;
  }
}
foreach($pictureKeywordArray as $key = > $picValue)
{
  foreach($picValue['keywords'] as $key = > $picIdValue)
  {
    if ($picIdValue == $searchIdKey)
    {
      echo $picValue['match'];
      $picValue['match']++;
      echo $picValue['match'];
    }
  }
}
foreach($pictureKeywordArray as $key = > $picValue)
{
  echo $picValue['match'];
}

I'm novice as you can see, When I echo the picValue['match'] in the foreach loop it gives me a correct value after "++". But then below when I call the array again it gives me the value of 4 instead of 5 as intended. Thanks in advance for any help with this.

Upvotes: 1

Views: 195

Answers (3)

Dmitri Gudkov
Dmitri Gudkov

Reputation: 2133

Cause you work with the item copy in first case try $pictureKeywordArray[$key]['match'] instead of $picValue['match']

Upvotes: 2

Matthew
Matthew

Reputation: 48304

foreach works on a copy of the data. You must use a reference to modify the original:

foreach ($foo as $i => &$f)
{
  $f++;
}

unset($f); // important to do this if you ever want to reuse that variable later 

Upvotes: 0

Naftali
Naftali

Reputation: 146320

In that second foreach you need to call it by reference:

foreach($pictureKeywordArray as $key => &$picValue) 
{                                       //^-- `&` makes it by reference
  foreach($picValue['keywords'] as $key => $picIdValue)
  {
    if ($picIdValue == $searchIdKey)
    {
      echo $picValue['match'];
      $picValue['match']++; //now updates what you want it to update
      echo $picValue['match'];
    }
  }
}

Upvotes: 1

Related Questions