Skip to content

Loose in_array(string, array, false) on array with mix of string and objects will __toString() those objects ONLY when the first array entry is an object #18625

@phoenixz

Description

@phoenixz

Description

The following code:

<?php
<?php
class Test {
    public function __toString(): string
    {
        die('fail!' . PHP_EOL);
    }
}

$a = [
    'string' => 'test', //  // <=== First position is a string
    'object' => new Test()
];

print_r(in_array('test', $a)); This displays "1", correctly.
echo PHP_EOL;
print_r($a); // This displays the array, correctly, all works as expected

$a = [
    'object' => new Test(), // <=== object is now on first position
    'string' => 'test',
];

print_r(in_array('test', $a)); // Script dies here with "fail!" because in_array() executed Test::__toString()
print_r($a);

Resulted in this output:

1
Array
(
    [string] => test
    [object] => Test Object
        (
        )

)
fail!

But I expected this output instead:

1
Array
(
    [object] => Test Object
        (
        )

    [string] => test
)
1
Array
(
    [object] => Test Object
        (
        )

    [string] => test
)

PHP Version

PHP 8.3.6 (cli) (built: Mar 19 2025 10:08:38) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.3.6, Copyright (c) Zend Technologies
    with Zend OPcache v8.3.6, Copyright (c), by Zend Technologies

Operating System

Ubuntu 24.04.2 LTS

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions