Note that there are some explanatory texts on larger screens.

plurals
  1. POCan't count an array in PHP
    text
    copied!<p>I've encountered a very odd issue in a class I'm creating. Here is a snippet of the class below and it's output:</p> <pre><code>class WeirdHappenings { protected $filters_list = array(); ... function build() { $filters_count = count($this-&gt;filters_list); echo "&lt;pre&gt;"; var_dump($this-&gt;filters_list); echo "&lt;br&gt;" . $filters_count . " is the count"; echo "&lt;/pre&gt;"; } } </code></pre> <p>Before you ask, yes filters_list is a populated array which is populated during the execution of the class. The Vardump proves that:</p> <pre><code>array(2) { ["filter_1"]=&gt; string(17) "calendar year nbr" ["filter_2"]=&gt; string(18) "reviewer type desc" } 0 is the count </code></pre> <p>How can this be possible? It's an array with two elements yet count can't tell me how big it is?</p> <pre><code>PHP 5.3.2-1ubuntu4.2 with Suhosin-Patch (cli) (built: May 13 2010 20:03:45) Copyright (c) 1997-2009 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies </code></pre> <p><code>error_reporting = E_ALL | E_STRICT</code></p> <p>This is the resolution:</p> <pre><code>class WeirdHappenings { protected $filters_list = array(); protected $thing = array("foo" =&gt; "bar", "ack" =&gt; "bar"); function WeirdHappenings() { } function makeMeCry() { $filters = array(); $filter_count = 1; $crapola = array("f1" =&gt; array("name" =&gt; "calendar year nbr"), "f2" =&gt; array("name" =&gt; "reviewer type desc")); foreach( $crapola as $key =&gt; $data ) { $filters["filter_$filter_count"] = $data['name']; $filter_count++; } $this-&gt;filters_list = $filters; } function build() { $filters_count = count($this-&gt;filters_list); $this-&gt;makeMeCry(); echo "&lt;pre&gt;"; var_dump($this-&gt;filters_list); var_dump($this-&gt;thing); echo "&lt;br&gt;" . $filters_count . " is the count of the filters"; echo "&lt;br&gt;" . count($this-&gt;thing) . " is the count of the thing"; echo "&lt;/pre&gt;"; } } $weirdthings = new WeirdHappenings(); $weirdthings-&gt;build(); </code></pre> <p>As pointed out in numerous comments the count was being performed prior to the population of the array.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload