Bret.burrill
Bret.burrill

Reputation: 41

Are keys inherent to arrays?

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.

Upvotes: 2

Views: 94

Answers (3)

Agnius Vasiliauskas
Agnius Vasiliauskas

Reputation: 11267

In the most basic sense - "key" is just an instruction for computer how to find required value in the array. So key is like an address of value cell. And you don't find a house in a city without an address - so you will likely don't find value in the array without a key either. Most programming languages supports plain arrays, where key is just an integer - 0,1,2,3,... Consider this array's element layout in memory:

Element index/key:  0 1 2 3 4
Value:              A B C D E

And when you ask for a computer - give me array[3] element - it knows that it needs to look at memory cell array_byte_offset_in_ram + size_in_bytes_of(array_element) * 3
Same instruction expressed in human language will be "find where first array element is stored in memory and jump from it forward in memory by 3x memory amount which is needed to store 1 array element". By doing this algo finds your cell and fetches your value D.

For arrays of arbitrary keys, when key can be any string - is another story. But idea remains the same - from the key computer should deduce How to find required element cell in memory. Usually this done by translating arbitrary string keys into integer hash values. Then sorting these hashes and performing binary search algorithm to find integer-index of required hash value. Last step is to pass index found into another plain array where your real values are stored.

Consider this array:

Element key: 'ABC' 'EFG' 'CDE'
Value:          a     b     c

There are many ways to calculate hashes, but for simplicity consider stupid hash function
hash(string) = sum(ascii_values_of_chars_in_string)

So we have following hash table:

hash('ABC') = ord('A')+ord('B')+ord('C')
hash('EFG') = ord('E')+ord('F')+ord('G')
hash('CDE') = ord('C')+ord('D')+ord('E')

After sorting hashes we generate and save such hash array:

hash[0] = 198
hash[1] = 204
hash[2] = 210

Now we can save array values into another plain array where integer index should be the same as hash array index of saved hash(key) function output =>

value[0] = 'a'
value[1] = 'c'
value[2] = 'b'

Now when you request - give me array['EFG'] value - computer calculates key 'EFG' hash which is 210. Then by employing binary search algo finds 210 value in hash table and deduces that it's index in hash table is 2. So it jumps to value table at index 2 by using above described technique of plain arrays and fetches resulting value of 'b' which will be returned to you.

These are the main principles of array keys. Of course there are much more things under the hood - such as hash collisions and etc. But at this point you don't need more complexities as for now. Simply keep in mind that at most bare-bones of computer architecture - there is only plain numbers and math operating on them - no fancy things like "strings"/"objects" and another cosmos :-)

Upvotes: 1

foobar
foobar

Reputation: 795

An array in PHP is actually an ordered map. A map is a type that associates values to keys.

PHP Documentation

This means that you can only have one index, however you need to be aware that arrays implement an internal pointer, and technically you can iterate the array by sequentially hopping through each array entry. This is what foreach does for you. You can check next documentation for more details.

In case if you don't supply keys when creating an array, then keys will be assigned automatically. Array created by the following line of code will assign index (key) for each of its elements (starting from 0):

$array = array("foo", "bar", "hello", "world");

Upvotes: 0

Diogo Santo
Diogo Santo

Reputation: 789

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!

Upvotes: 0

Related Questions