dtslobe4694 2018-10-02 15:28
浏览 116

数组固有的键吗?

It seems that all my questions are so basic that I can't find answers for them anywhere, probably because all the guides assume you have at least some basic knowledge. Anyway, on to my question...

With regard to PHP, are keys inherent to arrays? In other words, if I get data from a form that gives me a set of values in the $_POST array, are there keys assigned to the values by default, or do keys only exist if they are created explicitly? I am assuming there are no keys if I don't create them, but I suspect that there could be numerical keys assigned to each value automatically.

  • 写回答

3条回答 默认 最新

  • doudu22272099831 2018-10-02 15:40
    关注

    If you assign an existing array to a new variable, it will be like you copied that array to that variable. So let's say you have:

    $initialArray = ["test1" => "My First Test", "test2" => "My Second Test"];
    

    If you initialize a new variable and say it should be equal to the array you desire:

    $aNewArray = $initialArray;
    

    Your new array will be exactly like the one you said for it to copy; Also, if you change $initialArray after you copied to the $aNewArray, your changes will only affect the variable you change, keeping your $aNewArray with the same data before you changed.

    Now, if you just set a few variables into an array without specifying keys to access them, it will automatically link them by numeric index:

    $arrayWithoutSpecificKeys = ["one", "two", "three"];
    print_r($arrayWithoutSpecificKeys);
    

    This output will be:

    array (
         0 => "one",
         1 => "two",
         2 => "three"
    );
    

    Never forget array start with index 0;

    This means if you assign $_POST to a variable, it will inherit the key => values transmitted.

    In your form you will name you inputs like this:

    <input type="text" name="surname" .../>
    

    Your $_POST variable will have an array with whatever information you set in your input, and link them as bellow:

    ["surname" => "<your typed value>"]
    

    Then again, if you copy the $_POST to a variable, that variable will inherit all the content that $_POST contains;

    Hope it helped!

    评论

报告相同问题?