1

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.

3 Answers 3

2

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

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

2 Comments

+1. This (using a key) is often the cleanest solution. References can get messy.
in this variant $key is overridden cause used in both foreaches), we should be careful with this...
1

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'];
    }
  }
}

Comments

0

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 

Comments

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.