PHP で配列の要素を入れ替えるには
配列内の要素を入れ替えるには、以下を使用できます。
- 一時変数を使って入れ替える
$temp = $array[$index1];
$array[$index1] = $array[$index2];
$array[$index2] = $temp;
- list() 関数で入れ替える。
list($array[$index1], $array[$index2]) = array($array[$index2], $array[$index1]);
- array_splice() 関数を使って入れ替える
$temp = $array[$index1];
$array[$index1] = $array[$index2];
array_splice($array, $index2, 1, $temp);
配列の要素を交換します。arrayは交換する要素の配列、index1とindex2は交換する要素のインデックスです。