admin管理员组

文章数量:1389952

I am using this code as part of a navigation plugin i.e. previous, next for custom post types.

$pos = array_search( $post_id, $exhibs );
 if( $previous ) {
  $new_pos = $pos - 1;
  $class = 'nav-previous';
 } else {
  $new_pos = $pos + 1;
  $class = 'nav-next';
 }
 if( $exhibs[$new_pos] ) {

}

Which works fine but I am getting a notice PHP Notice: Undefined offset: -1 on this line:

 if( $exhibs[$new_pos] ) {

I think this only happens for the first object in my posts. Any ideas on how to fix this notice?

I am using this code as part of a navigation plugin i.e. previous, next for custom post types.

$pos = array_search( $post_id, $exhibs );
 if( $previous ) {
  $new_pos = $pos - 1;
  $class = 'nav-previous';
 } else {
  $new_pos = $pos + 1;
  $class = 'nav-next';
 }
 if( $exhibs[$new_pos] ) {

}

Which works fine but I am getting a notice PHP Notice: Undefined offset: -1 on this line:

 if( $exhibs[$new_pos] ) {

I think this only happens for the first object in my posts. Any ideas on how to fix this notice?

Share Improve this question asked Apr 9, 2020 at 18:33 JoaMikaJoaMika 6986 gold badges27 silver badges58 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

It depends on number of things

  • how you want to design, if this is the first post, does it still have previous class? Some design create loops, first post previous will go to the last post like a loop, some design does not display the previous button if it is the first one.
  • the design will then determine how you will code and create the logic for frontend

For instance, I guess your first $pos return 0;

$pos = array_search( $post_id, $exhibs );

 if( $previous ) {
  $new_pos = $pos - 1; // if first $pos is 0, the $new_pos is -1
  $class = 'nav-previous';
 } else {
  $new_pos = $pos + 1;
  $class = 'nav-next';
 }
 if( $exhibs[$new_pos] ) { // $exhibs[-1] does not exist, so undefined error occur

 }

Possible correction for avoiding error (it really depends on how you want to design)

if( $new_pos > 0 && $exhibs[$new_pos] ) {} 

// or 

if( isset( exhibs[$new_pos] ) {}

本文标签: PHP Notice Undefined offset 1Navigation PreviousNext