-1

I have foreach

foreach ($query->posts as $key => $value) {
                                if ($value->ID == $post->ID) {
                                    $nextID = $query->posts[$key + 1]->ID;
                                    $prevID = $query->posts[$key - 1]->ID;
                                    break;
                                }
                            }

but I have notice

Notice: Undefined offset: 3 in path...line 797

Notice: Trying to get property 'ID' of non-object in path... line 797

Why, and how fix?

Nazar
  • 11
  • 5
  • 1
    `$key + 1`. When you reach the last element in the array, what do you think this will be? You need to check if it exists before using it. Same goes for `$key - 1` and the first element. – El_Vanja Mar 14 '21 at 10:13

1 Answers1

0

It's difficult to get a hold of your code with what you've provided. As I don't which line from your snippet gives the error. However, there are a couple of places where this can happen.

$nextID = $query->posts[$key + 1]->ID;
$prevID = $query->posts[$key - 1]->ID;

You have a query, with an array of posts $query->posts, however, your doing a calculation based off the $key variable. For example. If there are 4 items in your array. The last $key variable will contain 3. But as your adding +1 it can not find that array item.

Try changing your code to something like:

<?php
declare(strict_types=1);

foreach ($query->posts as $key => $value) {
    $nextID = null;
    $prevID = null;

    if ($value->ID == $post->ID) {
        $hasNextId = isset($query->posts[$key + 1]);
        $hasPrevId = isset($query->posts[$key + 1]);

        $nextID = $hasNextId ? $query->posts[$key + 1]->ID : null;
        $prevID = $hasPrevId ? $query->posts[$key - 1]->ID : null;
        break;
    }
}

I have added to boolean variables, to check if the post as a previous ID (for the first array key). And if the post as a next ID (for the last array key).

If they don't have a next or prev ID, the value for $nextID and/or $prevID will be null. This will mitigate the error, however, it could break code further down the line. Please make sure to add appropriate checks for example:

old code:

echo "next is " . $nextID;

new code:

if ($nextID !=== null) {
    echo "next is " . $nextID;
}
xvilo
  • 396
  • 4
  • 14