Isla Isla - 4 years ago 201
PHP Question

PHP echo array?

Im new at this and not sure how to fill an array and echo it. Can someone please help me? :)

First my array, that I hope is retrieving info from my notes.txt-file, if there is any?! Im not sure if i need both declarations?:

$test = array();
$test[] = json_decode(file_get_contents($file), TRUE);


Anyway, this is the code for adding elements to the array, the input from the user:

$name = guestbook_input($_POST['name']);
$comment = guestbook_input($_POST['comment']);

$test[] = [
'name' => $name,
'comment' => $comment,
'ip' => $_SERVER['REMOTE_ADDR'],
'time' => date("y-m-d H:m")
];

// Write input to file
file_put_contents($file, json_encode($test));


This code works fine (I think) and writes to the file.

Finally Im trying to echo the array to a table like this:

<?php
$getfile = json_decode(file_get_contents('./notes.txt'), TRUE);
foreach ($getfile as $value): ?>
<tr>
<?php
echo '<td>';
echo $value['name'];
echo '</td>';
echo '<td>';
echo $value['comment'];
echo '</td>';
echo '<td>IP:';
echo $value['ip'];
echo "<br>Tid:";
echo $value['time'];
echo '</td>'?>

</tr> <?php endforeach; ?>


This code do print elements, but only for the first input in my guestbook. I have no idea if this is the right way to do this or not, but hopefully someone can help me with this, so I can get this right?!

Answer Source

First, your declaration and assignment:

$test = array();
$test[] = json_decode(file_get_contents($file), TRUE);

The function json_decode(), as you're calling it, returns an array, so it is not necessary to declare the variable first, but it is good practice to do so. However, in the function call, you are actually assigning the entire results to $test[0], since $test[] simply creates a new element with the next numeric index. The code where you assign the user input is correct, so it gets output correctly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download