Hedva Hedva - 3 months ago 9
HTML Question

HTML in for loop with variable

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.

Answer

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>';
}