What should a traveller do if he wants to pray `Isha’ behind someone who is praying Maghrib?
Question

I prayed Maghrib, then I stood up to pray `Isha’ with it, shortening the prayer, and I prayed behind a second jama`ah who were praying Maghrib; I prayed `Isha’ with them, shortening the prayer, although they were residents of that place. I joined them in the prayer in the second rak`ah, then sat for the first tashahhud, then we prayed another rak`ah, then the imam said the salaam and I said it with him. It is my prayer valid or do I have to repeat it? If I repeat the prayer, should I pray it with two rak`ahs or four?
Praise be to Allah.If a traveller prays behind an imam who is a resident, then he must offer the prayer in full with him, if he is offering the same prayer as the imam, and it is not permissible for him to shorten the prayer to two rak`ahs.
See the answer to question no. 21996 .
But if he is offering a different prayer, as mentioned in the question, then the one who is praying behind the imam has the choice between praying only two rak`ahs, or completing the prayer and making it four rak`ahs, after the imam says the salaam.
Shaykh Muhammad ibn `Uthaymin (may Allah have mercy on him) was asked about a traveller who entered the mosque, and found a group praying Maghrib, and he had already prayed Maghrib, so he joined them in prayer with the intention of praying `Isha’, and when the imam stood up for the third rak`ah, he remained seated, and he recited the tashahhud and the said the salaam. What is the ruling on that?
He replied:
If a traveller enters the mosque having already prayed Maghrib, and he finds them praying Maghrib, and he joins them with the intention of praying `Isha’, some of the scholars say that his joining them is not valid, because of the difference in intention and action. And some of them said that it is valid, so when the imam stands up for the third rak`ah, the one who joined the congregation should complete the tashahhud and say the salaam after two rak`ahs, and this is the correct view. Or he may stand up with the imam for the third rak`ah, then complete `Isha’ by adding a fourth.
End quote from Majmu` Fatawa ash-Shaykh al-`Uthaymin, 15/357.
Based on that, what the questioner did – which was shortening his prayer to two rak`ahs – is valid, and he does not have to repeat this prayer.
And Allah knows best.