Hello. Was hoping for some assistance.

Visitors can rank their top 5 favorite colors. Upon return, they can choose to re-rank these colors. I want to keep a site rank of favorite colors.

assume:
array $oldRank = "blue", "brown", "black", "orange", "red";

using a form, the same visitor enters these as his updated favorite colors:
array $newRank = "brown", "black", "pink", "purple", "green";

is there a function or method to report the difference in positions in an EFFICIENT way?

That is my question but if you would like more info on my self-admitted stupid thoughts, here's where my start is at right now.....

if (in_array($newRank[$i],$oldRank)) {......

to determine if each element in $newRank was an element in $oldRank. BUT, that presents two problems....
1) how do I determine the position of the element within $oldRank. key could be used but I don't think that would be efficient with the code I provided above.
2) how do I determine an element is in $oldRank but not $newRank without repeating the process but reversed?

Any help would be great and if I didn't explain clearly, please let me know and I'll try again. Thanks.

    Perhaps you are looking to use [man]array_diff/man?

    If that is not satisfactory (your users must be pretty picky 🙂 ), then you can just sort and then do a single pass through each array for an O(n log n) time solution.

    EDIT:
    Sorry, I misread your question.

    The way I see, it an O(n*n) solution should be satisfactory since you only have 5 elements each in two arrays.

    1) how do I determine the position of the element within $oldRank. key could be used but I don't think that would be efficient with the code I provided above.

    Instead of using in_array(), use [man]array_search/man.

    2) how do I determine an element is in $oldRank but not $newRank without repeating the process but reversed?

    Now using array_diff() would be a good idea.

      laserlight wrote:

      Instead of using in_array(), use [man]array_search/man.

      Now using array_diff() would be a good idea.

      Thanks.

      array_search was exactly the function I was looking for. After playing with it, I actually re-did the whole thing but both array_search & array_diff will be used in other places.

      Googled everything I could think of but this forum usually ends up giving me the right answer! Thanks again.

        So does this mean your issue is resolved? If so, don't forget to mark this thread resolved.

          Thanks. Wasn't aware of the RESOLVED link.

            Write a Reply...