user
How to display the content of an array in PHP?
alphonsio

To display the content of an array in PHP, there are several solutions:

  • print_r(): displays the content of a variable in a readable form.
  • var_dump(): displays the structured information of a variable, including its type and value.
  • var_export(): similar to var_dump(), but displays the result as valid PHP code.
  • json_encode(): output the array in JSON format.
  • foreach: display the array element by element with a loop.

In PHP, you can display the content of an array using several different methods depending on how you want the output to be formatted. Here are some common methods:

1. Using print_r()

  • This function prints human-readable information about a variable, including arrays.
$array = array("apple", "banana", "cherry");
print_r($array);

Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
)

2. Using var_dump()

  • This function gives detailed information about the variable, including data types and values.
$array = array("apple", "banana", "cherry");
var_dump($array);

Output:

array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(6) "banana"
  [2]=>
  string(6) "cherry"
}

3. Using var_export()

The output of var_export() is valid PHP code. This means you can take the output and use it directly in a script to recreate the variable.

$array = array("apple", "banana", "cherry");
var_export($array);

Output:

array (
  0 => 'apple',
  1 => 'banana',
  2 => 'cherry',
)
  • The output is valid PHP code that can be copied and pasted into a PHP script to recreate the array or variable.
  • It is more readable than var_dump() for structured output, but it is primarily useful when you want to see the code representation of the array.

4. Using json_encode()

  • If you want to output the array in JSON format, json_encode() is useful.
$array = array("apple", "banana", "cherry");
echo json_encode($array);

Output:

["apple","banana","cherry"]

5. Using a foreach loop

If you want to display the content in a more controlled format, you can use a foreach loop.

$array = array("apple", "banana", "cherry");
foreach ($array as $item) {
    echo $item . "<br>";
}

Output:

apple
banana
cherry

Summary:

  • print_r(): For a quick, human-readable output.
  • var_dump(): For detailed debugging information (data type, size, value).
  • var_export(): Displays the array as valid PHP code.
  • json_encode(): For JSON output.
  • foreach: For custom formatting when looping through array elements.