LoginSignup
26
24

More than 5 years have passed since last update.

PHP で array から要素を削除

Last updated at Posted at 2012-12-26

unset() で要素を削除した後、必要があれば array_values() で歯抜けになったのを詰めます。

$arr = array(0, 1, 2, 3);
unset($arr[1]);
foreach ($arr as $key => $value) {
  echo $key . ' => ' . $value . "\n";
}
// 0 => 0
// 2 => 2
// 3 => 3
$arr = array_values($arr);
foreach ($arr as $key => $value) {
  echo $key . ' => ' . $value . "\n";
}
// 0 => 0
// 1 => 2
// 2 => 3

array_splice() でもできますが、毎回インデックスを詰め直すため、複数のバラバラな要素を削除する場合はパフォーマンスが落ちるかもしれません。

しかし unset() って演算子なのか関数なのかよくわからなくて気持ち悪いですね。

参考
How to delete an element from an array in php? - Stack Overflow

26
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
24