note 121100 added to function.array
| From: | steve at websmithery dot co dot uk | Date: | Fri, 19 May 2017 09:08:08 +0000 |
| Subject: | note 121100 added to function.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-209065@lists.php.net to get a copy of this message | ||
It is worth noting that, where possible, PHP silently converts string keys into integers, e.g.
<?php
$foo = [
'7' => 'This key is a string'
];
print_r($foo);
?>
will output:
Array
(
[7] => This key is a string
)
Note: the key has been recast as an integer.
One consequence of this is that an array cannot have equal integer and string keys:
<?php
$foo = [
'7' => 'This key is a string',
7 => 'This key is an integer'
];
print_r($foo);
?>
will output:
Array
(
[7] => This key is an integer
)
PHP recasts the first, string key as an integer and so the second (integer) key overwrites it.
This may seem to be of little consequence as equal string and integer keys are, perhaps, unlikely,
but one unexpected result of this recasting is when the array_merge() function is used. When the
arrays are merged, string keys are unaffected, but integer keys are renumbered sequentially in the
resulting array. This means that if an array being merged has string keys, one of which just happens
to be recastable as an integer, then that particular key will change.
----
Server IP: 72.52.91.14
Probable Submitter: 2.24.6.236
----
Manual Page -- http://php.net/manual/en/function.array.php
Edit -- https://master.php.net/note/edit/121100
Del: integrated -- https://master.php.net/note/delete/121100/integrated
Del: useless -- https://master.php.net/note/delete/121100/useless
Del: bad code -- https://master.php.net/note/delete/121100/bad+code
Del: spam -- https://master.php.net/note/delete/121100/spam
Del: non-english -- https://master.php.net/note/delete/121100/non-english
Del: in docs -- https://master.php.net/note/delete/121100/in+docs
Del: other reasons-- https://master.php.net/note/delete/121100
Reject -- https://master.php.net/note/reject/121100
Search -- https://master.php.net/manage/user-notes.php