Tutorial :Multi-dimensional array keys - strange behaviour



Question:

I am using a multi-dimensional associative array to keep track of monthly totals, then I want to loop through it using foreach and output the contents.

The totals for each inner array are kept in element 12, and only want each array to output if the total is > 0, except "Total", which I want to output even if it is 0.

  foreach($yearspend as $key => $format)    {       // only show formats with any spend       if($key == "Total" || $format[12] > 0)       {          echo "<tr><td>$key</td>";          foreach($format as $value)          {             echo "<td>".number_format($value,2)."</td>";          }          echo "</tr>";       }    }  

For some reason this outputs for inner array 0, even though [0][12] is 0.

Here is the output from print_r:

Array  (      [0] => Array          (              [12] => 0          )        [Group] => Array          (              [12] => 0          )        [Total] => Array          (              [12] => 0          )  )  

Please can anyone help?


Solution:1

Try

 $key === "Total" ...  

When comparing a string and a number, PHP attempts to convert the string to a numeric type and then performs the comparison. The '===' operator compares the value and type, so a string will never equal a number.


Solution:2

Strings of characters evaluate to 0 in PHP if the value is not determined by the parser. ie "4" is the same as 4, but "Total" is treated the same as 0. So in PHP, the expression

"Total" == 0  

returns true.

You can correct this by using the === operator:

if ("Total" === 0)  

which returns false


Solution:3

Could this be a round error issue. Does it still go wrong if your condition is changed to...

if($key == "Total" || $format[12] > 0.001)  


Solution:4

Scott's answer will work ($key === "Total"). Or this:

if (strval($key) == "Total" || $format[12] > 0)  


Solution:5

i saw this comment on php's foreach documentation:

It should be noted that when using foreach to pass an array's key ($key => $value), the key must be a string and not binary content - containing 0's, f.e., as was my case when i used foreach to parse bencoded data handed back to me from a bittorrent tracker scraping - as this will throw foreach off and hand you a key that is binary different than the actual content of the array.

it's not an answer, but hopefully it will help you troubleshoot.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »