The php var_dump() function allows us to print information about the type and value of a variable.

$num = 5;
$string = "This is a string; 
$array = ["This","is","an","array"];

var_dump($num, $string, $array);

//Output:
int(5)
string(16) "This is a string"
array(4) {
  [0]=>
  string(4) "This"
  [1]=>
  string(2) "is"
  [2]=>
  string(2) "an"
  [3]=>
  string(5) "array"
}

When working with variables, the ability to easily be able to print out all information about a variable is very useful.

The php var_dump() function returns a data structure which includes information about the passed variables type and value.

With var_dump(), you can see the type and values of strings, ints, floats, arrays and objects.

Below is an example of using var_dump() to output different types of variables.

class exampleClass {
    public $id;
    private $name;
    static protected $multiplyNumbers;

    static function multiplyNumbers($a,$b) {
        return $a * $b;
    }
}

$num = 5;
$string = "This is a string";
$array = ["This","is","an","array"];

var_dump(new exampleClass);
var_dump($num);
var_dump($string);
var_dump($array);

//Output:
object(exampleClass)#1 (2) {
  ["id"]=>
  NULL
  ["name":"exampleClass":private]=>
  NULL
}
int(5)
string(16) "This is a string"
array(4) {
  [0]=>
  string(4) "This"
  [1]=>
  string(2) "is"
  [2]=>
  string(2) "an"
  [3]=>
  string(5) "array"
}

How to Print Arrays in php with var_dump() Function

We can print arrays in php is with the php var_dump() function.

As we know, var_dump() returns information about a variable that includes its type and value.

So, if you have an array, you can pass it to var_dump() and get a data structure which has the type and value of each of the elements of the array.

Below is an example in php showing how to print an array with var_dump().

$array = ["This","is","an","array"];

var_dump($array);

//Output:
array(4) {
  [0]=>
  string(4) "This"
  [1]=>
  string(2) "is"
  [2]=>
  string(2) "an"
  [3]=>
  string(5) "array"
}

Using var_dump() to Print Objects in php

If you have an object, you can pass it to var_dump() and get a detailed listing the public and private variables in the object.

Below is an example in php showing how to print an object with var_dump().

class exampleClass {
    public $id;
    private $name;
    static protected $multiplyNumbers;

    static function multiplyNumbers($a,$b) {
        return $a * $b;
    }
}

var_dump(new exampleClass);

//Output:
object(exampleClass)#1 (2) {
  ["id"]=>
  NULL
  ["name":"exampleClass":private]=>
  NULL
}

Hopefully this article has been useful for you to learn how to use the php var_dump() function to dump variable information.

Categorized in:

PHP,

Last Update: March 13, 2024