how could we echo 'a' with it's value 1 with function array_key_first in php

Viewed 25

On php.net the manual for the function.array-key-first shows the exemple below.

<?php
    $array = ['a' => 1, 'b' => 2, 'c' => 3];
    
    $firstKey = array_key_first($array);
    
    var_dump($firstKey);
    ?>
The above example will output:

string(1) "a"

What I want to know is how could we echo 'a' with it's value 1. The output would be a1.

As I was writing this I actually found a way to do it, however I can't find anything explaining why it works. Could someone explain to me why it works and if it's valid?

<?php
// Enter your code here, enjoy!
$array = ['a' => 1, 'b' => 2, 'c' => 3];

$firstKey = array_key_first($array);

echo array_key_first($array);
echo $array[array_key_first($array)];
?> 

Result for 8.1.10:
a1
1 Answers

If it works, the generally it's "valid" (which can be a bit of a subjective term), unless it shows up a security problem or something like that. But that definitely isn't an issue here.

Anyway it's relatively simple:

array_key_first returns the first key in the array, which of course is a.

So your code outputs a because you echo what array_key_first($array); returns. Then your code outputs 1 because you told it to get the value from the array at the key a. $array[array_key_first($array)] is the equivalent of writing $array["a"] because, again, array_key_first($array) returns a.

I hope this makes sense.

P.S. Your $firstKey = array_key_first($array); is actually redundant because you never use the $firstKey value you generated. But it could have a purpose - to save repeated calls to array_key_first, you could have written the code like this instead:

$firstKey = array_key_first($array);
echo $firstKey;
echo $array[$firstKey];
Related