Switching two variables with PHP
Published on 2026-01-04 • Modified on 2026-01-04
This snippet shows how to switc two variables with PHP.
<?php
declare(strict_types=1);
namespace App\Controller\Snippet;
/**
* I am using a PHP trait to isolate each snippet in a file.
* This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
* or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
* Services are injected in the main controller constructor.
*/
trait Snippet338Trait
{
public function snippet338(): void
{
$a = 555;
$b = 10001;
var_dump('a,b:', $a, $b);
[$a,$b] = [$b, $a];
echo PHP_EOL;
var_dump('a,b (after switch):', $a, $b);
// That's it! 😁
}
}
Run this snippet More on Stackoverflow Random snippet
Call to action
Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky 🦋
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges 🏅.
Thank you for reading! And see you soon on Strangebuzz! 😉