note 124505 added to function.array-fill-keys
| From: | Radon8472@php.net | Date: | Fri, 13 Dec 2019 13:44:35 +0000 |
| Subject: | note 124505 added to function.array-fill-keys | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-213512@lists.php.net to get a copy of this message | ||
This function has a undocumented behavoir when you use objects as value.
When you use objects as $value for array_fill_keys each entry of the new array is a reference to the
same object.
For this example-code, I expeced that each entry contains only one entry in "loop".
With the "array"-test this worked, but in the object-test not.
<?php
$keys = array("step1","step2");
$tests = array(
"array" => array_fill_keys($keys, array()),
"object"=> array_fill_keys($keys, new ArrayObject())
);
foreach($tests as $testName => $aData) {
foreach($aData as $k => &$v) {
$v["loops"][] = $k;
}
echo "Results for ".$testName."\n";
print_r($aData);
}
?>
But the Output was:
---------------------------------
Results for native_array
Array
(
[step1] => Array
(
[loops] => Array
(
[0] => step1
)
)
[step2] => Array
(
[loops] => Array
(
[0] => step2
)
)
)
Results for object
Array
(
[step1] => ArrayObject Object
(
[storage:ArrayObject:private] => Array
(
[loops] => Array
(
[0] => step1
[1] => step2
)
)
)
[step2] => ArrayObject Object
(
[storage:ArrayObject:private] => Array
(
[loops] => Array
(
[0] => step1
[1] => step2
)
)
)
)
---------------------------------
You can test it in multipe php-versions here:
https://3v4l.org/TpP3N
----
Server IP: 208.43.231.9
Probable Submitter: 185.85.3.195 (proxied: 92.193.201.228)
----
Manual Page -- http://php.net/manual/en/function.array-fill-keys.php
Edit -- https://master.php.net/note/edit/124505
Del: integrated -- https://master.php.net/note/delete/124505/integrated
Del: useless -- https://master.php.net/note/delete/124505/useless
Del: bad code -- https://master.php.net/note/delete/124505/bad+code
Del: spam -- https://master.php.net/note/delete/124505/spam
Del: non-english -- https://master.php.net/note/delete/124505/non-english
Del: in docs -- https://master.php.net/note/delete/124505/in+docs
Del: other reasons-- https://master.php.net/note/delete/124505
Reject -- https://master.php.net/note/reject/124505
Search -- https://master.php.net/manage/user-notes.php