Skip to content

SimpleXML: empty child element without attributes casts to true instead of false #21583

@Chi-teck

Description

@Chi-teck

The following code:

<?php

$cases = [
  '<foo><bar>content</bar></foo>',
  '<foo><bar/></foo>',
  '<foo/>',
];
foreach ($cases as $case) {
  \printf("%-30s: %s\n", $case, new \SimpleXMLElement($case)->bar ? '' : '');
}

Resulted in this output:

<foo><bar>content</bar></foo>  : ✅
<foo><bar/></foo>              : ✅
<foo/>                         : ❌

But I expected this output instead:

<foo><bar>content</bar></foo>  : ✅
<foo><bar/></foo>              : ❌
<foo/>                         : ❌

The documentation explicitly lists empty SimpleXML elements without attributes as falsy.
https://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

Image

PHP Version

any

Operating System

Debian 13

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions