How do <?php echo $i ? > be random between Y and X?

Asked

Viewed 86 times

0

I’m developing a layout, I need your class in div, be randomized between two names, I need a javascript to do this, someone can help me?

Ex.:

<div class="left"><div>
<div class="right"><div>
<div class="left"><div>
<div class="right"><div>
<div class="left"><div>
<div class="right"><div>

Obs.: Remembering that I need a function to insert, as I will use this in Wordpress...

Thank you

  • Are you looping in PHP? If so, then it’s better to use PHP for this than JS

  • Yes, in php, by wordpress...

  • You need JS for that. Do it in PHP itself

  • Show how you’re looping?

  • is a simple content loop.. of Wordpress posting content

  • 2

    You want "random" or "alternating"?

Show 1 more comment

2 answers

2

In addition to the form cited, there is another way also that is by checking whether a certain number is even or odd, for example:

PHP:

<?php

for ($i = 0; $i < 10; $i++) {
    /**
     * Caso o número seja par, define a classe como `right`;
     * Caso contrário, define como `left`.
     */
    $class = ($i % 2) ? 'right' : 'left';

    /**
     * Imprime a `div` com a classe e adiciona uma quebra
     * de linha com PHP_EOL
     */
    echo "<div class=\"{$class}\"><div>", PHP_EOL;
}

Javascript:

const container = document.querySelector("#container");

for (let i = 0; i < 10; i++) {
  container.insertAdjacentHTML('beforeend', `<div class="${i % 2 ? 'right' : 'left'}"><div>`);
}
#container {columns: 2}
.left,.right {height: 50px;width: 50px}
.left {background:red}
.right {background:yellow}
<div id="container"></div>

For more information on insertAdjacentHTML

0


Exemplifying with a looping while, which may be applied to any other.

Before looping set the value $i = 'left'; and can use <?=$i?> instead of <?php echo $i ?> if your server is set to accept:

<?php
$i = 'left';
while(condição):
?>
<div class="<?=$i?>">conteúdo da div</div>
<?php
   $i = $i == "left" ? "right" : "left";
endwhile;
?>

Place $i = $i == "left" ? "right" : "left"; at the end of the loop, which will alternate the value of $i every turn.

  • That almost worked Okay, this one with Loop, I already got the loop, I just needed the part to insert in the loop, can help me please?

  • Yes. What you need?

  • Dude, I got... thank you... I put "$i = $i == "left" ? " right: "left";" at the end of my loop, and the command worked... Thank you very much friend..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.