$viableparents is built as $value => $label
When you call the function you set the selected value, but you used end($viableparents), which is the label. It should be someting like:
end($viableparents);
$sel = key($arr);
Regarding the other part, if the key in the array is the category id, you can simply use $categoryid instead of $sel