tags:

views:

77

answers:

5

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?

+1  A: 

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.

Scott Saunders
All of what you say is true. But it won't address the problem. The condition is `if($key == "Total" || $format[12] > 0)` As soon as $key evalutates to "Total", the rest of the conditional is ignored.
dnagirl
That's what he wants though: "only want each array to output if the total is > 0, except "Total", which I want to output even if it is 0."
Scott Saunders
thanks - that works perfectly
malcomio
A: 

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)
rikh
+1  A: 

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

Travis
A: 

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

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

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.

Brandon H
i never make it in time. i get done my answer and suddenly "four new answers have been posted..." sheesh.
Brandon H