2

I know that if you manually declare the keys in your array, it is considered hash and if it is a self-generated key, it is an array(sequential). So what if I manually declare

$array1 = array(1 => 123, 2 => 312, 3 => 456);
// and
$array2 = array(123,312,456);

Questions:

  1. Is $array1 an array or hash?
  2. Is my idea on hash and array correct?
BlitZ
  • 12,038
  • 3
  • 49
  • 68
  • Check first comment here http://php.net/manual/en/function.is-array.php – elclanrs Jun 03 '13 at 03:47
  • 4
    PHP has no concept of hashes, a hash in PHP is simply an associative array. – sevenseacat Jun 03 '13 at 03:47
  • PHP does not have a notion of hashes. You should write your own classes representing `lists` (arrays) and `hashes` (associative arrays) in PHP in order to achieve what you want. – Nemoden Jun 03 '13 at 03:50
  • Please, explore relative question: [Does PHP handle numerically-indexed arrays differently (internally)?](http://stackoverflow.com/q/15614566/1503018) – sectus Jun 03 '13 at 04:37

1 Answers1

2

PHP uses only associative arrays. To determine if an array could be an indexed array from 0 to size - 1 eg an array where elements have been pushed, or added using array[] = x, the only method known is to check if all keys are from 0 to size - 1.

(Note that an array could be built via the "associative" way (ie providing both keys and values), using incremental keys from 0, and there is no way to determine that it was not built using the method given above (push or []), since, anyway, that makes no difference)

$i = 0;
foreach (array_keys($array) as $key) {
  if ($key !== $i) break;  // Note the !== (not !=)
  $i++;
}

if ($i == count($array)) {
  // looks like array was built using indexing (see text above)
}

The final test $i == count($array), if true, indicates that all keys where numeric, starting from 0, incremented by 1 for each element, until the last element.

Déjà vu
  • 28,223
  • 6
  • 72
  • 100