Question about array indices and values

per example 8.2 on this page: https://docstore.mik.ua/orelly/webprog/pcook/ch08_10.htm#phpckbk-CHP-8-EX-2 ,

I’m not really understanding why they are using strings as the index portion of the array function here. per this page: https://www.php.net/manual/en/function.array.php , if the index vals are omitted, integers are automatically generated. my question is this:

=> why do I have to have an array like this:

array('value 1' => 'pw 1', 'value 2' => 'pw 2');

when it is much easier to write this:

array('value 1', 'value 2', 'value 3');

??? is this just part of the syntax that PHP offers and there is nothing I can do about this semi-convolution? thanks.

Adam

I don’t think this question was very intuitive. so I’m going to discard it. anyone is welcome to respond, but I’m considering it irrelevant. sorry for posting it. I will deal with it accordingly.

Arrays in PHP is either a dictionary or an array list. Either way it has key-value pairs. So if you create an array with keys you get an array exactly as you declared it.

$list = [
  'key 1' => 'value 1',
  'key 2' => 'value 2',
  'key 3' => 'value 3'
];
[
  'key 1' => 'value 1',
  'key 2' => 'value 2',
  'key 3' => 'value 3'
]

But if you omit keys it will automatically insert integers so you still have key-value pairs

$list = [
  'value 1',
  'value 2',
  'value 3'
];
[
  0 => 'value 1',
  1 => 'value 2',
  2 => 'value 3'
]

This way handling arrays, iterating over them, referencing keys etc will still work.

You don’t. The example you linked to, using the username as the array index, has a very specific relationship between each index and value (username=>password), that allows the value to be directly tested/referenced via the index, that simplified and greatly sped up the operation of the code (no loop was needed to find values.) This is the same concept that is used with indexes in database tables. If you are not doing any direct referencing like this, then the example you linked to isn’t relevant.

thanks phdr. I think I understand what you are saying.

Sponsor our Newsletter | Privacy Policy | Terms of Service