Jump to content

Unsupported operand types: help!


stevieontario

Recommended Posts

Afternoon Freaks,

 

I have a script that dies at this point: 

			if ($a != 0)
					$ratio = $a/$b;

My script is supposed to process a bunch of XML, almost all of which is numerical (digits). However, at one point in the XML file, the value that $a represents is "N/A".

 

The script dies when it tries to execute line 128, i.e. at $ratio = $a/b;

 

The error message reads: 

 

"Fatal error: Unsupported operand types in /[path/file.php] on line 128"

 

My layman's guess is that php doesn't know what to do when I tell it to divide some number by "N/A".

 

Any ideas?

Link to comment
https://forums.phpfreaks.com/topic/282873-unsupported-operand-types-help/
Share on other sites

Correct -- you can't divide "N/A" by a number.  What do you want to happen in these cases?  You could first off check if it is a number with a php function like http://php.net/manual/en/function.is-numeric.php

 

You could also force php to cast "N/A" to an integer or a real, which would be 0.

 

 

$ratio = (float)$a/$b;

 

...or you could have some code like this:

 

 

$a = ($a == 'N/A' ? 1 : $a);

thanks everyone. How about if a value is just empty? I neglected to view the source of the XML table. In source files that work, here's how the XML looks: 

<Output>
<Hour>1</Hour>
<Energy>0</Energy>
</Output>

... and here's how it looks when I'm getting that error:

<Output>
<Hour>1</Hour>
</Output>

i.e., there is no Energy data. Not even a tag. Somehow, that translates into "N/A" on the web table.

 

How do I handle this? My script is looking for some data in the Energy tag, but there isn't even an Energy tag.

perhaps

$str = "<Data>
<Output>
<Hour>1</Hour>
<Energy>0</Energy>
</Output>

<Output>
<Hour>1</Hour>
</Output>
</Data>";

$xml = simplexml_load_string($str);
foreach ($xml->Output as $op) {
    $hr = isset($op->Hour) ? $op->Hour : 0;
    $en = isset($op->Energy) ? $op->Energy : 0;
    $ratio = floatval($hr) && floatval($en) ? $en/$hr : 0;
    echo $ratio.'<br>';
}
  • 2 weeks later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.