ペチパーノート

WEB開発系Tipsブログです。

error_logに配列を出力する

Ajax通信やスマホアプリのAPIPHPで作る場合など、
画面にデバッグ情報を出せない場合があります。
そういう時は、Apacheerror_logにデバッグ情報を出力するのが手っ取り場合です。

test.php

<?php
$weight = 100;
error_log($weight);

error_log

100

この流れで配列を出力してみます。

test.php

<?php
$myself = array(
    'height' => 175,
    'weight' => 100,
    'salary' => 120000,
);
error_log($myself);

error_log

PHP Warning:  error_log() expects parameter 1 to be string

怒られました。こんな時は配列にprint_rをかましてさらに第二引数にtrueです。

test.php

<?php
$myself = array(
    'height' => 175,
    'weight' => 100,
    'salary' => 120000,
);
error_log(print_r($myself, true));

error_log

Array\n(\n    [height] => 175\n    [weight] => 100\n    [salary] => 120000\n)\n

これでOKです。
テキストエディタで改行コードを置換するとさらに見やすくなります。

Array
(
    [height] => 175
    [weight] => 100
    [salary] => 120000
)