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

0

I'm developing a layout, I need your class in the div, be random between two names, I need a javascript to do this, can anyone 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>

Note: I need a function to insert, because I will use this in Wordpress ...

Thank you

    
asked by anonymous 10.04.2018 / 22:54

2 answers

1

Exemplifying with a loop while , which can be applied to any other.

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

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

Put $i = $i == "left" ? "right" : "left"; at the end of the looping, which will toggle the value of $i at each turn.

    
10.04.2018 / 23:24
2

In addition to the form of the above, there is also another way that is to check if a given 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

    
11.04.2018 / 05:02