Advertisement
Advertisement


How to echo or print an array in PHP?


Question

I have this array

Array
(
  [data] => Array
    (
      [0] => Array
        (
          [page_id] => 204725966262837
          [type] => WEBSITE
        )

      [1] => Array
        (
          [page_id] => 163703342377960
          [type] => COMMUNITY
        )
      )
)

My question is how can I just echo the content without this structure? I tried

foreach ($results as $result) {
    echo $result->type; 
    echo "<br>";
} 
2019/05/31
1
203
5/31/2019 11:48:27 PM

Accepted Answer

This will do

foreach($results['data'] as $result) {
    echo $result['type'], '<br>';
}
2012/03/22
129
3/22/2012 5:29:06 AM


If you just want to know the content without a format (e.g. for debuging purpose) I use this:

echo json_encode($anArray);

This will show it as a JSON which is pretty human readable.

2014/01/07

There are multiple function to printing array content that each has features.

Prints human-readable information about a variable.

$arr = ["a", "b", "c"];
echo "<pre>";
print_r($arr);
echo "</pre>";
Array
(
    [0] => a
    [1] => b
    [2] => c
)


var_dump()

Displays structured information about expressions that includes its type and value.

echo "<pre>";
var_dump($arr);
echo "</pre>";
array(3) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
}


var_export()

Displays structured information about the given variable that returned representation is valid PHP code.

echo "<pre>";
var_export($arr);
echo "</pre>";
array (
  0 => 'a',
  1 => 'b',
  2 => 'c',
)

Note that because browser condense multiple whitespace characters (including newlines) to a single space (answer) you need to wrap above functions in <pre></pre> to display result in correct format.


Also there is another way to printing array content with certain conditions.

echo

Output one or more strings. So if you want to print array content using echo, you need to loop through array and in loop use echo to printing array items.

foreach ($arr as $key=>$item){
    echo "$key => $item <br>";
}
0 => a 
1 => b 
2 => c 
2018/10/14

You can use print_r, var_dump and var_export funcations of php:

print_r: Convert into human readble form

<?php
echo "<pre>";
 print_r($results); 
echo "</pre>";
?>

var_dump(): will show you the type of the thing as well as what's in it.

var_dump($results);

foreach loop: using for each loop you can iterate each and every value of an array.

foreach($results['data'] as $result) {
    echo $result['type'].'<br>';
}
2019/08/21

Did you try using print_r to print it in human-readable form?

2015/07/15

foreach($results['data'] as $result) {
    echo $result['type'], '<br />';
}

or echo $results['data'][1]['type'];

2012/03/22

Source: https://stackoverflow.com/questions/9816889
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]