Voting

: min(five, five)?
(Example: nine)

The Note You're Voting On

theking2 at king dot ma
5 months ago
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
)

<< Back to user notes page

To Top