he was, and he thought that he was Zayd but it turned out that he was Amr, his prayer is valid. This is like believing that the imam was white when he turned out to be black, or that he was wearing a wrap when it turned out to be a cloak, and similar mistaken assumptions that do not undermine the validity of following him in prayer.
But if his intention was to pray behind Zayd, and he would not have prayed behind him had he known that he was Amr, then, if the imam was Amr, he has not taken him as his imam. Actions are judged only by intentions. Is he then regarded as someone who prayed without following an imam, or is his prayer invalid? There is disagreement concerning this, just as there is when the imam’s prayer is invalid and the person following him is unaware of it.
Thus, not knowing the imam’s identity does not harm the person following him, provided that his intention is to pray behind the imam leading that congregation. Likewise, the imam is not harmed by not knowing the identities of those following him; rather, if he intends to lead those behind him in prayer, that is valid.
It has also been said that if he specifies a particular person but is mistaken, his prayer is invalid in all cases.
The correct view is to distinguish between specifying someone as the object of his intention—meaning that he intends to pray behind no one else—and identifying someone merely by assumption—meaning that he intends to pray behind the imam, whoever he may be, but assumes that he is Zayd. And Allah knows best.