22
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

explode()の挙動がキモい

Last updated at Posted at 2014-02-26

explode()で空文字列""を分解しようとすると、「空文字を要素として含む配列」が返ってくる。

var_dump(explode(' ', ''));

//array("")

この挙動がキモイというか、不便。。個人的には「空配列」になってほしいと思う。
implode()とexplode()を重ねると、元の配列に戻らない。。

$arr = array();
$str = implode(' ', $arr);
var_dump($str); //(空文字)

$arr = explode(' ', $str);
var_dump($arr); //[''] ←ちょwwww

面倒くさいけど3項演算子を合わせて防ぐ感じかな。

$arr = array();
$str = implode(' ', $arr);
var_dump($str); //(空文字)

$arr = ($str==='') ? array() : explode(' ', $str);
var_dump($arr); //(空配列)

$str ? で条件判定に手抜きをすると、$str==='0'だったときに判定が逆転しておかしくなります。

22
21
8

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
22
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?