如何访问由findAll生成的数组中的元素

I have to test if my current users exists in other table or not? how to access to getId in the userOldList list: the following code produce an erro :HTTP ERROR 500

$user = new User();
$repositoryUserOld= $this->getDoctrine()->getRepository(userOld::class);
$userOldList   = $repositoryUserOld->findAll();

$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
if ($form->isSubmitted() && $form->isValid()) {

    foreach ($userOldlList as $userO ) {

        If ($user->getId() == $userO->getId() )
       {
           $form->get('id')->addError(new FormError('User exists'));
           return $this->render('AppBundle:MyApp:user.html.twig', array('form' => $form->createView()));
       }
   }

In foreach you are using variable $userOldlList (note l between Old and List), but at the top you define variable $userOldList. I think that's why you get error 500.

As for the how to do that more efficiently, this could can replace whole foreach block (only condition in if is a new code; inner block is a copy from your question without any changes):

if ($repositoryUserOld->find($user->getId()) {
    $form->get('id')->addError(new FormError('User exists'));
    return $this->render('AppBundle:MyApp:user.html.twig', array('form' => $form->createView()));
}

BTW, originally I just copy-pasted your code into a new file in PhpStorm, and it highlighted misspelled variable right away. Having a tool that checks your code as you type it is a great way to improve your productivity.