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.

2 Answers 2

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>';
}
Sign up to request clarification or add additional context in comments.

1 Comment

You just made me really happy. Sometimes the solutions are much easier than I think they are.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.