How to find whether the term is first or last in a vocabulary?
First, you need to obtain one level of your taxonomy terms. Use either taxonomy_get_tree($vid, 0, 1); for top level ones, or taxonomy_get_children($tid) for children of a known element.

It should be sorted the way you want it, as both functions contain this in their code:

$query-&gt;orderBy('t.weight');
$query-&gt;orderBy('t.name');


Now you can use standard PHP functions reset(array &amp;$array) and end(array &amp;$array) to get first and last object from that array for comparison. Note that this will move internal pointer around, so don't use them lightly on arrays you also use elsewhere already.