-1

If I have an array defined like this in PHP:

$stocked = [];
array_push($stocked, "beer");
array_push($stocked, "chocolate");

How do I print out the array? I tried using echo, but it just gives "Array". What I want is for the output to be ["beer", "chocolate"].

Adam Lau
  • 153
  • 2
  • 10

3 Answers3

2

To get the exact output you requested, you could encode the array as JSON, e.g.

echo json_encode($stocked);
ADyson
  • 57,178
  • 14
  • 51
  • 63
1
<?php
$stocked = [];
array_push($stocked, "beer");
array_push($stocked, "chocolate");

echo "<pre>";
print_r($stocked);

echo '<br>';
echo $stocked[0].'<br>';
echo $stocked[1];
   
?>

Output:-

Array
(
    [0] => beer
    [1] => chocolate
)

beer
chocolate
KUMAR
  • 1,993
  • 2
  • 9
  • 26
0

You can use the following functions:

var_dump();
print_r();  // You can use these with <pre> tags to get prettier output : echo "<pre>" . print_r($yourArray, true) . "</pre>";
dd(); // Note: this will halt the execution.
Tushar
  • 665
  • 5
  • 11