返回循环前的循环次数

时间:2017-07-26 15:58:33

标签: php loops for-loop if-statement

我正在尝试在循环中返回产品数量并在循环之前输出。下面总是返回0,所以有没有办法可以延迟输出,直到它完成循环后?

if( $post_objects ):
$prodcount = 0;
?>

<h1>There are <?php echo $prodcount ?> items</h2>

<?php foreach( $post_objects as $post_object): ?>

<p>something</p>

<?php $prodcount++ ?>

<?php endforeach; ?>

<?php endif; ?>

2 个答案:

答案 0 :(得分:1)

非常简单,只需count()数组,并将其用作v ariable。

<?
if( $post_objects ):
?>
    <h1>There are <?php echo count($post_objects); ?> items</h2>
<?php 
    foreach( $post_objects as $post_object): 
?>
        <p>something</p>
<?php 
        $prodcount++
    endforeach;
endif;

答案 1 :(得分:0)

foreach遍历数组时,不确定为什么要尝试重新发明轮子,而不是在该数组上使用普通的count()

$prodcount = count($post_objects);

http://php.net/manual/en/function.count.php