count()值和foreach()循环之间的差异计数

时间:2014-08-14 13:21:53

标签: php loops foreach count

好吧,这超出了我的想象。我必须遗漏一些明显的东西,但我找不到,是什么。

a)PHP脚本:

echo('<pre>count($connectionsData) = '.print_r(count($connectionsData), TRUE).'</pre>');

$cnt = 0;

foreach($connectionsData as $connection)
{
    echo('<pre>'.(++$cnt).'. '.print_r($connection, TRUE).'</pre>');
}

b)结果:

count($connectionsData) = 1

1. 1
2. 1
3. 8
4. 1

如果可能,count在某个变量上返回1一个),然后,当同一个变量放入foreach时,那个循环实际上是四次次?

1 个答案:

答案 0 :(得分:3)

似乎$connectionsData是一个没有实现countable interface的对象:

class Obj{
    public $var = 1;
    public $var2 = 2;

}

$obj = new Obj();

echo 'count: ' . count($obj) . '<br>';

$count=0;
foreach($obj as $el){
    echo ++$count . ' element: ' . $el . '<br>';
}

class CountableObj implements Countable{
    public $var = 1;
    public $var2 = 2;
    public function count(){ 
        return 2; 
    } 

}

$obj = new CountableObj();

echo 'count countable: ' . count($obj) . '<br>';

$count=0;
foreach($obj as $el){
    echo ++$count . ' element: ' . $el . '<br>';
}

直播示例:http://codepad.viper-7.com/q7sNol