In the name of Allaah and peace and blessings be upon the Messenger of Allaah: I entered the mosque to perform the Thuhr prayer and when the Imaam recited the Takbeerat Al-Ihraam and did not perform the Rukoo‘ (i.e. bowing), I realized that he was performing the funeral prayer, so I changed my intention to that of performing the funeral prayer. After the Tasleem, I performed the Thuhr prayer. What is the religious ruling in this regard? What if I entered the mosque and found the worshippers performing the funeral prayer and I had not performed the obligatory prayer yet; should I join the funeral prayer and then perform the obligatory prayer afterwards?
All perfect praise be to Allaah, The Lord of the worlds. I testify that there is none worthy of worship except Allaah, and that Muhammad, sallallaahu ‘alayhi wa sallam, is His slave and messenger.
If one changes his intention from performing one obligatory prayer to another, in such a case the two obligatory prayers are invalid.
Ibn Qudaamah said in Al-Mughni, "If one proclaimed the Takbeerat Al-Ihraam (i.e. the initial 'Allaahu Akbar') intending to perform an obligatory prayer and then changed his intention to that of performing another obligatory prayer, the first is invalidated since he changed his intention and the second is invalid as well because he did not intend it from the beginning (of the prayer)."
Hence, what you did was correct as you performed the Thuhr prayer after finishing the funeral prayer. Your funeral prayer is invalid since you did not intend to perform it while reciting the Takbeerat Al-Ihraam as your intention was to perform the Thuhr prayer. However, you cannot make up for it.
As for the second case mentioned in your question, the best thing to be done in such a case is to join the funeral prayer as it may be missed if you perform the Thuhr prayer first thus giving it precedence.
Added to that, you should seek the great rewards for performing the funeral prayer over a dead Muslim. The Messenger of Allaah, sallallaahu ‘alayhi wa sallam, said: "Whoever attends the funeral (of a Muslim) till the prayer is offered for (the dead), for him is the reward of one Qiraat and whoever accompanies the funeral procession (of a Muslim) and remains with it till the funeral prayer is offered and the burial ceremonies are over, for him is the reward of two Qiraats." It was asked, "What are two Qiraats?" He, sallallaahu ‘alayhi wa sallam, replied: "Like two huge mountains." [Al-Bukhari and Muslim] This is the wording cited by Imaam Muslim .
You can search for fatwa through many choices