2

Okay, so I have an array named with three values:

$tutorials = array('introduction', 'get_started', 'basics')

I also have a link for example:

mysite.com/?tutorials=get_started

So the link above appears to be the first value of $tutorials but what if I want my anchor's href to be like the next value?

<a href="?tutorials=basics">Next</a>

Are there any shortcuts for this? Because my array is not just only 3 but 20 and I don't want to edit them one by one.

What I'm trying to do here is a Next and Previous links. Please help.

Thank you!

0

3 Answers 3

1

Something like this should work:

<?php

   $value = $_GET['tutorials']; // get the current

   // find it's position in the array
   $key = array_search( $value, $tutorials );

   if( $key !== false ) {
      if( $key > 0 ) // make sure previous doesn't try to search below 0
          $prev_link = '?tutorials=' . $tutorials[$key-1];

      if( $key < count( $tutorials ) ) // Make sure we dont go beyond the end of the array
          $next_link = '?tutorials=' . $tutorials[$key+1];
   } else {
      // Some logic to handle an invalid key (not in the array)
   }

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

1 Comment

Yay! Thank you! I just didn't know about array_search. Newbie here.
1

Retrieve the index of the current item in your array, and add 1 to get the index of the following tutorial.

Don't forget to check if you already are on the latest item of the array.

<?php

$tutorials = array('introduction', 'get_started', 'basics');

$index = array_search($_GET['tutorials'], $tutorials);

if ($index === FALSE) {
    echo 'Current tutorial not found';
} else if ($index < count($tutorials) - 1) {
    echo '<a href="?tutorials=' . $tutorials[$index+1] . '">Next</a>';
} else {
    echo 'You are already on the latest tutorial available';
}

Manual

1 Comment

Okay, I get it now. But I think there's a little mistake you have there.
0

Use array_search() to get the key and add / minus one to the key to get the next / previous link:

$key = array_search($_GET['tutorials'], $tutorials);

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.