-1

I did look up this error and people say that it is caused by an empty array, but as you can see, I have entries for my array. Or that the variable isn't an array, which it is. I am unsure as to why this doesn't work. Any help would be greatly appreciated.

<? php 
    $posts = array();
    $posts[0] = array(
        'user' => 'Bob',
        'message' => 'This is a post',
        'image' => 'image/picture.jpg',
        'date' => '20/4/17');
    $posts[1] = array(
        'user' => 'James',
        'message' => 'This is also a post',
        'image' => 'image/picture.jpg',
        'date' => '20/4/15');
    $posts[2] = array(
        'user' => 'Steve',
        'message' => 'This is also also a post',
        'image' => 'image/picture.jpg',
        'date' => '20/4/13');

?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Social Media</title>
    <link rel="stylesheet" href="style/style.css">
  </head>
  <body>
    <h1> Social Media </h1>
    <?php foreach ($posts as $post){?>
    <p>
        <?= $post['user'] ?>
        <?= $post['message'] ?>
        <?= $post['date'] ?>
        <?= $post['image'] ?>
    </p>
    <?php } ?>

  </body>
</html>
MLJezus
  • 79
  • 1
  • 9

3 Answers3

0

You have array of array for that you have to specify which array value you want to echo like,

echo $post[0]['user'];

It will print user from $posts[0].

<?php
 $c = 0;
 foreach ($posts as $post){?>
<p>
    <?= $post[$c]['user'] ?>
    <?= $post[$c]['message'] ?>
    <?= $post[$c]['date'] ?>
    <?= $post[$c]['image'] ?>
</p>
<?php
$c++;
 } ?>
Abhishek Gurjar
  • 7,426
  • 10
  • 37
  • 45
0

I've actually tested above code and I dont see any issue with your code but its possible that you've turned all your error_reporting to E_ALL or something but anyways you can try below make sure to check if the object is an array or not

if (is_array($posts)) 
{
  foreach ($posts as $post)
  {
       //do something
   }
}
Fernan Vecina
  • 144
  • 1
  • 8
0

@mim. noticed a stray space in the opening php tag, removing it fixed this problem.

MLJezus
  • 79
  • 1
  • 9