-1

I am very new to PHP and hope you can help me with this.

I am fetching some data from SQL and try to create an array that I want to echo on a page.

When I echo the result from the following ($output) then this only returns the word "array" insteaed of the items that I am trying to add to it.

Can someone tell me what I am doing wrong here and provide me a short explanation as well ?

$c = "";
$i = 0;
$arr = array();
$output = ''
foreach ($objNames->names as $names) {
    $c = "<img src='images/photos/photo_" . str_replace(" ", "_", $names->member) . ".png' alt='' class='clickable flagLink trackHC' />&nbsp;" . $names->member . " &nbsp;&nbsp;";
    array_push($arr, $c);
    $i++;
}
if($i != 0) {
    $output = $arr;
}


<div id="output"><?php echo $output; ?></div>

Many thanks for any help, Mike.

Mike
  • 815
  • 7
  • 15
  • 23

3 Answers3

3

You cant just echo arrays.

You have to loop through it with a foreach for example:

$c = "";
$i = 0;
$arr = array();
$output = ''
foreach ($objNames->names as $names) {
    $c = "<img src='images/photos/photo_" . str_replace(" ", "_", $names->member) . ".png' alt='' class='clickable flagLink trackHC' />&nbsp;" . $names->member . " &nbsp;&nbsp;";
    array_push($arr, $c);
    $i++;
}
if($i != 0) {
    $output = $arr;
}

foreach($output as $row) {
?>
    <div id="output"><?php echo $row; ?></div>
<?php
}

This should work for you!

Sean Kendle
  • 3,538
  • 1
  • 27
  • 34
Xatenev
  • 6,383
  • 3
  • 18
  • 42
  • Thanks a lot for the quick help ! One more question on this. Will this echo everything to the same div (which is what I need) or will it create multiple divs ? – Mike May 13 '14 at 17:42
  • multiple divs. put the div tags **outside** the `foreach` loop if you want printing everything in the same div – Luis Masuelli May 13 '14 at 17:55
  • 1
    @Mike You have to see it like this: You are taking EVERY element in this array now. and for EACH element in this array, you are executing the code in the {} braces – Xatenev May 13 '14 at 17:57
2

An array must be printed using:

print_r($arrayValue)

you can keep the print value also (EDITED):

$x = print_r($arrayValue, true)

but I prefer the json way if it's for logging purposes:

echo json_encode($arrayValue)

keeping in mind every value must be json-serializable.

...

Doing a plain echo $arrayValue will always print "Array" word without any content. Yes, it's a bit unintuitive (since other languages like python don't behave like that) but it is what it is.

Luis Masuelli
  • 12,079
  • 10
  • 49
  • 87
0

If you wish to just see/print the contents of your array, try this:

print_r ($output);
Populus
  • 7,470
  • 3
  • 38
  • 54
Nawed Khan
  • 4,393
  • 1
  • 10
  • 22