You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
<?php<?phpclass Test {
publicfunction__toString(): string
{
die('fail!' . PHP_EOL);
}
}
$a = [
'string' => 'test', // // <=== First position is a string'object' => newTest()
];
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' => newTest(), // <=== 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
The text was updated successfully, but these errors were encountered:
@phoenixz It's not about the object being (or not being) on the first place, but that the string you are looking for was already found (in_array stops checking other items as it can already return true).
Indeed. As explained, nothing surprising is going on here. Loose in_array() comparison does string coercion, and it does so element by element. If your __toString() exists the script, there's nothing we can do about that.
Description
The following code:
Resulted in this output:
But I expected this output instead:
PHP Version
Operating System
Ubuntu 24.04.2 LTS
The text was updated successfully, but these errors were encountered: