note 129853 added to function.array-keys
| From: | theking2@king.ma | Date: | Wed, 13 Nov 2024 16:22:34 +0000 |
| Subject: | note 129853 added to function.array-keys | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221650@lists.php.net to get a copy of this message | ||
PHP arrays are weird. So the result of
<?php
$array = [
'element0',
'element1' => 'Hello World',
'element2' => 42,
'element3' => [ 'aaa', 'bbb' ],
];
print_r( array_keys($array) );
?>
is a surprising though correct
Array
(
[0] => 0
[1] => element1
[2] => element2
[3] => element3
)
Arrays in php are really ordered key value pairs where if a value is missing it will become a value
with a number as key. To get the intuitive first dimension of an array use a map with function to
determine if a key is in fact an index.
This
<?php
$array_first = array_map(
fn ($key)=>
is_int($key)?$array[$key]:$key
,
array_keys($array)
);
print_r($array_first);
?>
will show
Array
(
[0] => element0
[1] => element1
[2] => element2
[3] => element3
)
However in a niche case
<?php
$array = [
'element0',
'element1' => 'Hello World',
'element2' => 42,
'element3' => [ 'aaa', 'bbb' ],
12 => 'I\'m a field, not a key'
];
?>
this won't work of course and output
Array
(
[0] => element0
[1] => element1
[2] => element2
[3] => element3
[4] => I'm a field, not a key
)
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.137 (proxied: 83.97.87.43)
----
Manual Page -- https://php.net/manual/en/function.array-keys.php
Edit -- https://main.php.net/note/edit/129853
Del: integrated -- https://main.php.net/note/delete/129853/integrated
Del: useless -- https://main.php.net/note/delete/129853/useless
Del: bad code -- https://main.php.net/note/delete/129853/bad+code
Del: spam -- https://main.php.net/note/delete/129853/spam
Del: non-english -- https://main.php.net/note/delete/129853/non-english
Del: in docs -- https://main.php.net/note/delete/129853/in+docs
Del: other reasons-- https://main.php.net/note/delete/129853
Reject -- https://main.php.net/note/reject/129853
Search -- https://main.php.net/manage/user-notes.php