0

I was wondering if it was possible to use HTML inside a for loop while using a variable.

So this works at the moment:

<?php
[...]

for ($x=0 ; $x <= $nr_of_bookitems; $x +=2) {
    echo get_book($x)->meta_value;
}

[...]
?>

But this doesn't give me the result I want, because I want it to be urls.

So I want it like this:

<?php
[...]

for ($x=0 ; $x <= $nr_of_bookitems; $x +=2) {
    <a href="<?php echo get_book($x)->meta_value;; ?>" target="_blank">Text</a>
}

[...]
?>

But this doesn't work because I haven't close the php tags and HTML doesn't do anything. But when I close the php tags, it seems I can't use the variable $x anymore:

<?php
[...]

for ($x=0 ; $x <= $nr_of_bookitems; $x +=2) ?>
    <a href="<?php echo get_book($x)->meta_value;; ?>" target="_blank">Text</a>

<?php 
}

[...]
?>

I couldn't find a solution on the internet. I do have seen some examples with foreach like this one, but i'm not sure how to use that in this case if even possible.

Community
  • 1
  • 1
Hedva
  • 317
  • 1
  • 3
  • 15

2 Answers2

1

Try this:

for ($x=0 ; $x <= $nr_of_bookitems; $x +=2)
{
    $meta_value = get_book($x)->meta_value;
    echo '<a href="' . $meta_value . '" target="_blank">Text</a>';
}
Asmir Zahirovic
  • 267
  • 2
  • 11
  • 1
    You just made me really happy. Sometimes the solutions are much easier than I think they are. – Hedva Aug 28 '16 at 01:32
0

This should work as well:

for ($x=0 ; $x <= $nr_of_bookitems; $x +=2)
{
    ?>
    <a href="<?php echo get_book($x)->meta_value;; ?>" target="_blank">Text</a>
    <?php 
}

I think the only problem was you left off the opening curly bracket.

jmdev
  • 1
  • 1