Trending algorithm in PHP?

Simple answer: Figure out the system first, then figure out how to do it in PHP.
Write down your system in English (or your chosen language. You know what i mean.). Make all decisions (even if you change them later, make A decision for now).
Once you’ve defined your rules, it’s basic word-problem solving. Take each step/rule and reduce it to code. When you get to the end, you’ve got your code.