var_dump() in PHP

1️⃣ What is var_dump()?

  • var_dump() is a PHP built-in function.
  • It displays detailed information about a variable, including:
    • Data type (string, integer, array, boolean, etc.)
    • Value of the variable
    • Length (for strings or arrays)

It’s mainly used for debugging during development.


2️⃣ Syntax

var_dump($variable);

  • $variable = any PHP variable you want to inspect.

3️⃣ Examples

Example 1 – Integer

<?php
$age = 25;
var_dump($age);
?>

Output:

int(25)

  • int → data type
  • 25 → value

Example 2 – String

<?php
$name = "Saravana";
var_dump($name);
?>

Output:

string(8) "Saravana"

  • string → data type
  • (8) → number of characters
  • "Saravana" → value

Example 3 – Boolean

<?php
$isActive = true;
var_dump($isActive);
?>

Output:

bool(true)


Example 4 – Array

<?php
$colors = array("Red","Green","Blue");
var_dump($colors);
?>

Output:

array(3) {
  [0]=> string(3) "Red"
  [1]=> string(5) "Green"
  [2]=> string(4) "Blue"
}

  • array(3) → 3 elements
  • Shows index [0], [1], [2], type, and value of each element

4️⃣ Why use var_dump()?

  1. Debugging variables: Know exactly what type and value a variable has.
  2. Inspect arrays or objects: See nested structures clearly.
  3. Avoid errors: Check before using variables in calculations or functions.

Tip: You can also use print_r() to display arrays, but var_dump() gives more detailed info, including types.