0
1

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 1 year has passed since last update.

行数を節約するvar_dump()を書いてみた

Last updated at Posted at 2022-06-27
../

var_dump()で配列をダンプすると、やたらと行数が長い。出力制御関数ob_start()ob_get_clean()で挟み込めばテキストが取れると聞いたので、行数をほぼ1/2にするものを書いてみた。引数は1つに限定。

function var_dump2($arg): void {
  ob_start(); 
  var_dump($arg); 
  $t = ob_get_clean();
  $s = '';
  while (($n = strpos($t, '=>')) > 0){
    // $s .= substr($t, 0, $n) . "=> ";
    $s .= rtrim(substr($t, 0, $n)) . " => ";
    $t = ltrim(substr($t, $n + 3));
  }
  echo $s, $t, PHP_EOL;
}

以下のようにpreg_replace()を使うとシンプルに書けるみたい。空白文字の処理が不完全かもしれないが。

function var_dump3($arg): void {
  ob_start(); 
  var_dump($arg); 
  // echo preg_replace("/=>[\r\n\s]+/", " => ", ob_get_clean()), PHP_EOL;
  echo preg_replace("/=>[\s]+/", " => ", ob_get_clean()), PHP_EOL;
}

Userの配列を通常のvar_dump()でダンプすると、以下の感じ。なお、私の環境はxdebugが入っていて、シンプルな出力形式になっていたことを知った。「xdebugがPHP環境に入っているかどうかでvar_dump()の出力形式が変わる」を参照のこと。

Sample.php:74:
array(2) {
  [0] =>
  class samples\User#3 (3) {
    private $mail =>
    string(11) "aaa@xxx.com"
    private $id =>
    string(4) "U001"
    private $name =>
    string(7) "Aさん"
  }
  [1] =>
  class samples\User#2 (3) {
    private $mail =>
    string(11) "bbb@xxx.com"
    private $id =>
    string(4) "U002"
    private $name =>
    string(7) "Bさん"
  }
}

作成したvar_dump2()だと、以下の感じ。几帳面な日本人は、きっとこっちの方が好き。

Sample.php:75:
array(2) {
  [0] => class samples\User#3 (3) {
    private $mail => string(11) "aaa@xxx.com"
    private $id => string(4) "U001"
    private $name => string(7) "Aさん"
  }
  [1] => class samples\User#2 (3) {
    private $mail => string(11) "bbb@xxx.com"
    private $id => string(4) "U002"
    private $name => string(7) "Bさん"
  }
}
../
0
1
3

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?