Why does PHP return zero by subtracting elements from an object?

Asked

Viewed 100 times

0

I noticed a behavior of PHP that I did not know, is the following:

to exemplify I am taking an XML and using the function simplexml_load_string(). See below(ignore the lack of checks, it’s just an example):

$simplexml_load_string = simplexml_load_string($my_xml_url);

if(isset($simplexml_load_string->item))
{
    $myarray = array();
    foreach($simplexml_load_string->item as $key => $value){
        $myarray['myelement'] = $value->myelement;  // 0 or 0.0
        $myarray['myelement2'] = $value->myelement2; // 0.000091
    }
}

So far I have an array $myarray with the key element myelement and the key element myelement2 with the values that can be commented in the above code, which are respectively "$value->myelement == 0 or 0.0" and "$value->myelement2 == 0.000091". Now I will try to make an account with the elements of $myarray down below.

$result = $myarray['myelement2'] - $myarray['myelement'];
// $result recebe 0

So I did some testing to understand what was going on, first I checked the accuracy in php.ini, it was OK, then I gave one echo 0.000091 - 0; or echo 0.000091 - 0.0; and received 0.000091 as expected. So I went to check the $myarray and I realized that the elements of the array were not common values, but "Simplexxmlelement Object([0] => 0.000091)", which makes perfect sense, since it assigns an element of the object returned by the xml function, but I still didn’t understand what happened to receive 0 forever (and I still don’t know). But I decided to take the test below:

$simplexml_load_string = simplexml_load_string($my_xml_url);

if(isset($simplexml_load_string->item))
{
    $myarray = array();
    foreach($simplexml_load_string->item as $key => $value){
        $myarray['myelement'] = (float)$value->myelement;  // 0 or 0.0
        $myarray['myelement2'] = (float)$value->myelement2; // 0.000091
    }
}
$result = $myarray['myelement2'] - $myarray['myelement'];
// $result recebe 0.000091

And my problem was solved, but the doubt continues, because PHP returns me 0 when it is a "Simplexxmlelement Object([0] => 0.0)" and returns me the value waiting when it is a "float"?

  • 1

    apparently it is a bug in php as you can see in this topic (this in English) https://stackoverflow.com/questions/18035163/php-read-decimal-integers-from-xml-attributes

  • Thank you for the link.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.