LoginSignup
4
8

More than 5 years have passed since last update.

【PHP】変数の内容を出力する関数いろいろ

Posted at

公式サイトには「変数操作 関数」として紹介されています。

変数操作 関数

var_dump

変数に関する情報をダンプします。変数の型も分かるので、重宝してます。

出力した変数ごとに改行されるので、情報量は多いですが見やすいです。
一度に複数の引数を指定することも可能です。

php.net〜var_dump

<?php
$test_str  = 'test';
$test_int  = 1;
$test_bool = true;

$test_array = array(
    'test' => array(1, '2', 'aaa', false, 'true')
);

var_dump($test_str);
// 出力結果:string(4) "test"

var_dump($test_int);
// 出力結果:int(1)

var_dump($test_bool);
// 出力結果:bool(true)

var_dump($test_array);
/*
出力結果
array(1) {
  ["test"]=>
  array(5) {
    [0]=>
    int(1)
    [1]=>
    string(1) "2"
    [2]=>
    string(3) "aaa"
    [3]=>
    bool(false)
    [4]=>
    string(4) "true"
  }
}
*/

/*
この書き方も使えます!
var_dump($test_str, $test_int, $test_bool, $test_array);
*/

print_r

指定した変数に関する情報を解りやすく出力します。var_dumpより情報量は少ないですが、レイアウトが見やすいです。

自動的に改行されないので、連続して複数の変数を出力する場合はecho "\n";を使用した方が良いかもしれません。

一度に複数の変数を指定することはできません。

php.net〜print_r

<?php
$test_str  = 'test';
$test_int  = 1;
$test_bool = true;

$test_array = array(
    'test' => array(1, '2', 'aaa', false, 'true')
);

print_r($test_str);
echo "\n";
// 出力結果:test

print_r($test_int);
echo "\n";
// 出力結果:1

print_r($test_bool);
echo "\n";
// 出力結果:1

print_r($test_array);
echo "\n";
/*
出力結果
Array
(
    [test] => Array
        (
            [0] => 1
            [1] => 2
            [2] => aaa
            [3] => 
            [4] => true
        )

)
*/

var_export

変数の文字列表現を出力、または返します。返される表現は有効なPHPコードです。(そのまま変数に代入することができます。)

あまり使いませんが・・・

こちらも自動的に改行されないので、連続して複数の変数を出力する場合はecho "\n";を使用した方が見やすいです。

一度に複数の変数を指定することはできません。

php.net〜var_export

<?php
$test_str  = 'test';
$test_int  = 1;
$test_bool = true;

$test_array = array(
    'test' => array(1, '2', 'aaa', false, 'true')
);

var_export($test_str);
echo "\n";
// 出力結果:'test'

var_export($test_int);
echo "\n";
// 出力結果:1

var_export($test_bool);
echo "\n";
// 出力結果:true

var_export($test_array);
/*
出力結果
array (
  'test' => 
  array (
    0 => 1,
    1 => '2',
    2 => 'aaa',
    3 => false,
    4 => 'true',
  ),
)
*/
4
8
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
4
8