Trending algorithm in PHP?

StarLion is right.
You must write down the Logic Flow in English first.
And hence you can figure out the algorithm.