Skip to content

Commit c633283

Browse files
authored
Merge pull request #29 from yt2951/main
Add swapping variables example
2 parents 8930bb7 + ef7c147 commit c633283

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -486,6 +486,41 @@ list($a, $b, $c, $d) = $array; // PHP Warning: Undefined array key 3
486486
// $d = null;
487487
```
488488

489+
You can also swap variables with destructuring assignments, considering you have variable like:
490+
```php
491+
$a = 'foo';
492+
$b = 'bar';
493+
```
494+
495+
So if you want to swap `$a` and `$b` instead of using a temporary variable like this:
496+
497+
```php
498+
$temp = $a;
499+
$a = $b;
500+
$b = $temp;
501+
502+
// $a = 'bar'
503+
// $b = 'foo'
504+
```
505+
506+
You can swap it using the list syntax:
507+
508+
```php
509+
list($a, $b) = [$b, $a];
510+
511+
// $a = 'bar'
512+
// $b = 'foo'
513+
```
514+
515+
Or since PHP 7.1, the shorthand syntax:
516+
517+
```php
518+
[$a, $b] = [$b, $a];
519+
520+
// $a = 'bar'
521+
// $b = 'foo'
522+
```
523+
489524
#### Associative array
490525

491526
![php-version-71](https://shields.io/badge/php->=7.1-blue)

0 commit comments

Comments
 (0)