-1

I am trying to find the most liked comment and make it the first. But I ran into the error

Undefined offset: 0

foreach ($clone_questions as $k => $valQuestion) {
    $likesCount = 0;
    $keyElement = 0;
    foreach ($valQuestion['answers'] as $key => $answer) {
        if ($likesCount < $answer['likesCount']) {
            $likesCount = $answer['likesCount'];
            $keyElement = $key;
        }
    }
    $best = $questions[$k]['answers'][$keyElement];
    unset($questions[$k]['answers'][$keyElement]);
    array_unshift($questions[$k]['answers'], $best);
}
zajonc
  • 1,935
  • 5
  • 20
  • 25
Sergey
  • 17
  • 7
  • 1
    Does this answer your question? ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – Nico Haase Sep 03 '21 at 09:08

2 Answers2

0

Add a check before unshifting that a better answer has been found

foreach ($clone_questions as $k => $valQuestion) {
    $likesCount = 0;
    $keyElement = 0;
    foreach ($valQuestion['answers'] as $key => $answer) {
        if ($likesCount < $answer['likesCount']) {
            $likesCount = $answer['likesCount'];
            $keyElement = $key;
        }
    }
    if($keyElement != 0) {
        $best = $questions[$k]['answers'][$keyElement];
        unset($questions[$k]['answers'][$keyElement]);
        array_unshift($questions[$k]['answers'], $best);
    }
}

If no better answer is found, you dont have to unshift anything (and avoid the error).

N69S
  • 16,110
  • 3
  • 22
  • 36
0

Probably variables $clone_questions and $questions contain the same values but different keys. It is probably the effect of data cloning.

The offset 0 is exists in array $clone_questions but you are trying to get value from the $questions. It would be best to ensure that both arrays contain identical keys.

If you have no influence on creating a copy of the table, then before the code below you need to obtain the correct key in the $questions table (e.g. by searching for it based on the value of $valQuestion)

$best = $questions[$k]['answers'][$keyElement];
unset($questions[$k]['answers'][$keyElement]);
array_unshift($questions[$k]['answers'], $best);

Your code at this point should look something like this

$questionKey = HERE YOU NEED TO GET THE CORRECT KEY IN $questions ARRAY

$best = $questions[$questionKey]['answers'][$keyElement];
unset($questions[$questionKey]['answers'][$keyElement]);
array_unshift($questions[$questionKey]['answers'], $best);
zajonc
  • 1,935
  • 5
  • 20
  • 25