Skip to content

Instantly share code, notes, and snippets.

@ytkhs
Last active December 16, 2015 02:03
Show Gist options
  • Save ytkhs/7650c0286fa439c1f02a to your computer and use it in GitHub Desktop.
Save ytkhs/7650c0286fa439c1f02a to your computer and use it in GitHub Desktop.
PHP:listを使って配列の順番を任意に入れ替える ref: http://qiita.com/qube81/items/aab9803c64a1068c769b
// これを
$x = ['PHP', 'Ruby', 'Perl'];
// こうしたい
$x = ['PHP', 'Perl', 'Ruby'];
// まともに入れ替える
$temp = $x[1];
$x[1] = $x[2];
$x[2] = $temp;
var_dump($x);
array(3) {
[0]=>
string(3) "PHP"
[1]=>
string(4) "Perl"
[2]=>
string(4) "Ruby"
}
list($x[0], $x[2], $x[1]) = $x;
array(3) {
[0] =>
string(3) "PHP"
[1] =>
string(4) "Perl"
[2] =>
string(4) "Perl"
}
//PHP 7.0.0RC6
list($x[0], $x[2], $x[1]) = $x;
array(3) {
[0] =>
string(3) "PHP"
[1] =>
string(4) "Ruby"
[2] =>
string(4) "Ruby"
}
list($x[0], $x[1], $x[2]) = [$x[0], $x[2], $x[1]];
// または
list($x[0], $x[2], $x[1]) = $x + [];
// PHP5, PHP7どちらでも同じ結果
array(3) {
[0] =>
string(3) "PHP"
[1] =>
string(4) "Perl"
[2] =>
string(4) "Ruby"
}
// PHPではこういう書き方ができない
$x[0], $x[1], $x[2] = $x[0], $x[2], $x[1];
# => PHP Parse error: syntax error, unexpected ','
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment