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
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);
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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>';
}
Edited by Barand
Link to comment
Share on other sites

  • 2 weeks later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.