How to set an Arrays internal pointer to a specific position? PHP/XML

前端 未结 8 1466
花落未央
花落未央 2020-12-01 01:16

Im trying to build a little site using XML instead of a database.

I would like to build a next and prev button which will work relative to the content I have displa

8条回答
  •  佛祖请我去吃肉
    2020-12-01 01:58

    If your array is always indexed consistently (eg. 'page1' is always at index '0'), it's fairly simple:

    $List = array('page1', 'page2', 'page3', 'page4', 'page5');
    $CurrentPage = 3; // 'page4'
    
    while (key($List) !== $CurrentPage) next($List); // Advance until there's a match
    

    I personally don't rely on automatic indexing because there's always a chance that the automatic index might change. You should consider explicitly defining the keys:

    $List = array(
        '1' => 'page1',
        '2' => 'page2',
        '3' => 'page3',
    );
    

    EDIT: If you want to test the values of the array (instead of the keys), use current():

    while (current($List) !== $CurrentPage) next($List);
    

提交回复
热议问题