Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
How to find the previous or next key in an array()
  • Hello,

    I would like to make some sortable stuff with "Up" and "Down" Buttons, for changing order of the actual and next or previous database enty.

    The picture shows how the backend looks like.

    My idea is to find out the IDs for the NEXT and PREVIOUS entry regarding the actual order [= Reihenfolge in my Pic].

    How can I do that? As you can see I have selected the IDs and order in an array, as I think that this could help.

    Is this a good way or is there (as most of the time) some cool Fuel stuff, which help me in that matter?

    Thanks
    Kay
  • There are currently no methods available in the Arr class to do this, so you'll have to code up your own method for doing this.
  • ok, do you have any idea HOW I can do that?

    I have not found anything useful to find out the previous and next IDs  in that array.
    Any Idea?
  • Are these arrays indexed or assoc?
  • Actually it's indexed with the IDs of the Model, but they are not in a complete order.
    (see my picture, there is a dump)

    If it is better I can switch that also to an "ordered" array.
  • Here you go...

    // return the key or value before whatever is in $current
    public function previous($array, $current, $use_key = false)
    {
        // we'll return null if $current is the first in the array (there is no previous)
        $previous = null;

        foreach ($array as $key => $value)
        {
            $matched = $use_key ? $key === $current : $value === $current;
            if ($matched)
            {
                return $previous;
            }
            $previous = $use_key ? $key : $value;
        }

        // we'll return false if $current does not exist in the array
        return false;
    }

    // return the key or value after whatever is in $current
    public function next($array, $current, $use_key = false)
    {
        $found = false;

        foreach ($array as $key => $value)
        {
            // $current was found on the previous loop
            if ($found)
            {
                return $use_key ? $key : $value;
            }
            $matched = $use_key ? $key === $current : $value === $current;
            if ($matched)
            {
                $found = true;
            }
        }

        if ($found)
        {
            // we'll return null if $current was the last one (there is no next)
            return null;
        }
        else
        {
            // we'll return false if $current does not exist in the array
            return false;
        }
    }

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion