too long

I have some legacy code that uses each to return menu item values

function fetch () {

    $item = each( $this->menu );
    if ( $item ) {
        return ( $item['value'] );
    } else {
        reset ( $this->menu );
        return false;
    }
}

I tried to solve this by adding a function that emulates the each function:

function each_replacement($arr) {
    $key = key($arr);
    $result = ($key === null) ? false : [$key, current($arr), 'key' => $key, 'value' => current($arr)];
    next($arr);
    return $result;
}

And changing the original function fetch to this (found this in another thread:

function fetch () {

    $item = this->each_replacement( $this->menu );
    if ( $item ) {
        return ( $item['value'] );
    } else {
        reset ( $this->menu );
        return false;
    }
}

But the output is not correct, it only shows the first menu item repeatedly and gets stuck in endless loop, so that doesn't work.

My preference is just to rewrite the code and tried some things like

foreach ($this->menu as $item) {  }

instead of

$item = each( $this->menu )

But that gave me this error:

Uncaught Error: Cannot use object of type MenuItem as array

If anyone can help me come up with a solution that would be great.

The complete menu code is here: http://sandbox.onlinephpfunctions.com/code/45a3c9c5c24232096744ecd9b915b13982ec551a

About the code:

  1. each() - Return the current key and value pair from an array and advance the array cursor

  2. current() - Return the current element in an array

  3. next() - Advance the internal pointer of an array

Which means each() = current() val following by a next() call

~

Note: I would use a foreach, this is just an explanation how to keep the fetch() function.

Code:

    /**
     * Iterates over the menu array
     * @return mixed item from menu
     * @access public
     */
    function fetch () {

        $item = current($this->menu);
        if ( $item ) {
            next($this->menu);
            return $item;
        }
        reset($this->menu);
        return false;

    }

Test here