0
$array=array('menu1','menu2','menu3','menu4','menu5','menu6','menu7','menu8','menu9','menu10');

I storied some menu names into an array, Then output some like

enter image description here

in diffirent page, the menu always show 5 items and current page is always 2nd.

enter image description here

And if the current page is in this case, it will loop display menu1, menu2, menu3 after menu10.

foreach($array as $k=>$r){
    if($r==$current){
        $n=$k;//count current memu position
    }
}
echo '<ul>';
foreach($d as $k=>$r){
    if($n>1&&$n<7){//normal situation like first image
        if($k==($n-1)){
            echo '<li><a>'.$r.'</a></li>';
        }else if($k==$n){
            echo '<li class="current">'.$r.'</li>';
        }else{
            echo '<li><a>'.$r.'</a></li>';
        }
    }else{
        //How to do in the case of the second image?
    }
}
echo '</ul>';

2 Answers 2

1

I think you would also like the menu look like this when the current selection is menu1:

menu10
menu1 [selected]
menu2
menu3
menu4

Here is the algorithm. It looks confusing but I am sure you can figure it out.

$array=array('menu1','menu2','menu3','menu4','menu5','menu6',
               'menu7','menu8','menu9','menu10');

$current = 'menu1';


$startIndex = array_search($current, $array)-1;
$total = count($array);
$result = array();

for($index = $startIndex ; $index <$startIndex+5; $index++){

    $result[] = $array[($index+$total)%$total];  //using % operator

}


print_r($result);
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

if($k==($n-1)){
    echo '<li><a>'.$r.'</a></li>';
}else if($k==$n){
    echo '<li class="current">'.$r.'</li>';
}else{
    if($k >= count($d)-1)
        echo ''<li><a>'.$d[$k-count($d)+1].'</a></li>';
    else
        echo ''<li><a>'.$r.'</a></li>';
}

This actually should work for both cases, so you can remove the big if statement and put this as the body of your foreach.

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.