如何使用php计算数组内容并指定数字位置

am working on a website project in which i fetch array from my database and use foreach statement to output its contents. I want use php script to count how many items are in the array and assign number position to each item so that if the number position of the first item is an odd number i will apply css float:left style to it but if its even number it will float:right

any help please??. thank you.

I think you can also use jquery with :odd selector.

You can do it with css only:

.list:nth-child(odd) {float:left;}
.list:nth-child(even) {float:right;}

Use the modulus operand:

<?php foreach ( $array as $index => $item ): ?>
    <div class="<?php echo $index % 2 ? 'even' : 'odd'; ?>"></div>
<?php endforeach; ?>

Then just use those class names in your CSS:

.odd {  float: left }
.even { float: right }

CSS3 has nice features (.list:nth-child(odd) {float:left;} .list:nth-child(even) {float:right;} ), but beware that this will not work on many browsers (ie8 and below, older firefox, etc) .. at least every user with WinXP+IE will see just a normal list without the different colors.

jQuery (also noted here) can also select with $('.xy:odd').css({'float':'left'}); , but if you are not using jQuery in your project its just a big (90kb jQuery library) overhead. Performance is also better if going with php.

So you better go with php and the modulo operand (if $count % 2), see Joseph Silber's answer here.