-3

I have a php script to echo out a set number of posts per page:

<div class="posts">
    <?php echo $post[1]; ?>
    <?php echo $post[2]; ?>
    <?php echo $post[3]; ?>
    <?php echo $post[4]; ?>
</div>

This works fine, but I'd like to hold the data in a seperate php section, and then echo it out using a simple statement. So for this I created:

$posts = "".$post_single[1];$post_single[2];$post_single[3];$post_single[4];."";  // Error On This Line

<div class="posts">
    <?php echo $posts; ?>
</div>

Whe I run this, I get the error Parse error: syntax error, unexpected '.' in ...

Any ideas how I can fix this to echo out the $posts line correctly?

W.H.
  • 17
  • 6

6 Answers6

4

; indicates the end of a statement. . concatenates two strings. You are confusing the two.

$posts = "" . $post_single[1] . $post_single[2] . $post_single[3] . $post_single[4] . "";

That said, concatenating empty strings on to the start and end is pointless. So don't do that.

$posts = $post_single[1] . $post_single[2] . $post_single[3] . $post_single[4];

And that said, concatenating everything in an array by explicit index is very long-winded. There is a function designed for that.

$posts = implode($post_single);

Note this will also include $post_single[0] which you were ignoring.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks. This solution works great, although I can't use the `implode` version as `$single_post[0]` is used further up in the page, and is therefore not needed in the `$posts` string – W.H. Jun 13 '18 at 08:10
1

you're not echoing correctly, you need to concat each variable, for example:

$stringOne = 'hello';
$stringTwo = 'world';

echo $stringOne. ' ' .$stringTwo; # this will output hello world;

so in your case:

$posts = "".$post_single[1];$post_single[2];$post_single[3];$post_single[4];."";

should be

$posts = "".$post_single[1]. $post_single[2]. $post_single[3]. $post_single[4] ."";
treyBake
  • 6,440
  • 6
  • 26
  • 57
0

Do it like this:

$posts = "".$post_single[1]."".$post_single[2]."".$post_single[3]."".$post_single[4];

<div class="posts">
    <?php echo $posts; ?>
</div>
Himanshu Upadhyay
  • 6,558
  • 1
  • 20
  • 33
0

How about a loop ? Something like this

<div class="posts">
    <?php 
       foreach ($posts as $post) {
         echo $post;
       }
     ?>
</div>
Gregoire Ducharme
  • 1,095
  • 12
  • 24
0

In place of this:

$posts = "".$post_single[1];$post_single[2];$post_single[3];$post_single[4];."";

try this:

$posts = $post_single[1].$post_single[2].$post_single[3].$post_single[4];

or this:

$posts = "{$post_single[1]}{$post_single[2]}{$post_single[3]}{$post_single[4]}";
0

Instead of this :

$posts = "".$post_single[1];$post_single[2];$post_single[3];$post_single[4];."";

try this :

$posts = "".$post_single[1] . $post_single[2] . $post_single[3] . $post_single[4]."";

use . operator to concat the variables.

<div class="posts">
    <?php echo $posts; ?>
</div>