php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #52482 Casting SimpleXMLElement('0') to boolean results in true
Submitted: 2010-07-29 10:50 UTC Modified: 2010-07-29 12:40 UTC
Votes:2
Avg. Score:3.0 ± 2.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: sjon at react dot com Assigned:
Status: Open Package: SimpleXML related
PHP Version: Irrelevant OS: Linux
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: sjon at react dot com
New email:
PHP Version: OS:

 

 [2010-07-29 10:50 UTC] sjon at react dot com
Description:
------------
I understand the bug I am reporting is described in the manual, which is why I am reporting it as a feature request. When casting SimpleXMLElements to boolean, most values comply with the way PHP casts them. There is however one exception: the string '0' is cast to true, which is unexpected. This is especially annoying when using XmlRpc, which uses <boolean>0</boolean> for its values.

Test script:
---------------
<?php

var_dump((bool)new SimpleXMLElement("<w>0</w>"));

Expected result:
----------------
bool(false)

Actual result:
--------------
bool(true)

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-07-29 11:02 UTC] salathe@php.net
You are not casting the string "0" to boolean, you're casting the object. As such, 
it follows normal rules for casting objects. The only time a SimpleXMLElement will 
cast to boolean false is with an "empty" element (e.g. "<w/>").

If you want your sample element to cast to false, you will first need to cast to a 
string: (bool) (string) new SimpleXMLElement...
 [2010-07-29 11:12 UTC] sjon at react dot com
Then why does this work correctly?

var_dump((int)new SimpleXMLElement("<w>2</w>")); (returns int(2))

The reason is SimpleXMLElements do not follow the normal rules, have a look at simplexml.c line 1762:

    if (type == IS_BOOL) {
        node = php_sxe_get_first_node(sxe, NULL TSRMLS_CC);
        prop_hash = sxe_get_prop_hash(readobj, 1 TSRMLS_CC);
        INIT_PZVAL(writeobj);
        ZVAL_BOOL(writeobj, node != NULL || zend_hash_num_elements(prop_hash) > 0);
        zend_hash_destroy(prop_hash);
        efree(prop_hash);
        return SUCCESS;
    }
 [2010-07-29 12:40 UTC] salathe@php.net
I didn't mean to suggest this wasn't worth considering.  I'm just wondering 
whether this particular suggestion might cause some impact for folks who already 
make use of the current behaviour.
 
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Sun Apr 21 08:01:25 2019 UTC