Home>

I also want to display the key name from the PHP array
Without changing the way the code below is added to the array
How can I retrieve the key name as well?
I would appreciate it if you could let me know.

<? php
$fruit = [];
$fruit ["aaa"] = "apple";
$fruit ["bbb"] = "Grape";
$fruit ["ccc"] = "lemon";
foreach ($fruit as $value) {
echo $value;// I want to display key names (aaa, bbb, ccc) in addition to apples, grapes, and lemons.
}
?>
php
  • Answer # 1

    If you don't understand grammatically, be sure to check the official documentation/manual.

    foreachThe description about is described here. The following is a part of the explanation.
    If this document alone doesn't make sense,Associative arrayIf you search using the keyword, many articles will appear, so it will be helpful.

    The second form also assigns the key of the current element to the variable $key at each iteration.

    The following is an example of code that also retrieves the key name

    <? php
    $fruit = [];
    $fruit ["aaa"] = "apple";
    $fruit ["bbb"] = "Grape";
    $fruit ["ccc"] = "lemon";
    foreach ($fruit as $key =>$value) {
        echo "Value is {$value}, Key is {$key}";
        echo PHP_EOL;
    }

    Output result

    Value is apple, Key is aaa
    Value is Grape, Key is bbb
    Value is lemon, Key is ccc


    Operation sample --paiza.io

  • Answer # 2

    Is it like this? You can retrieve both with key =>value.

    <? php
    $fruit = [];
    $fruit ["aaa"] = "apple";
    $fruit ["bbb"] = "Grape";
    $fruit ["ccc"] = "lemon";
    foreach ($fruit as $key =>$value) {
    echo $key. "=>". $Value;
    }
    ?>

    Retrieving keys and values ​​with a foreach statement --Repeat--Introduction to PHP