WordPress: PHP code rendering in the wrong place

It’s because you’re echoing a function that itself echoes a value. The function has a display parameter that you have to set to false if you want it to return it’s value to use it that way:

function the_ratings($start_tag = 'div', $custom_id = 0, $display = true)

Also –

if($category->cat_ID = 4)

should be:

if($category->cat_ID == 4)