php - PHP 中的数值数组和关联数组是两种不同的东西吗?

标签 php arrays

这是对我之前在这里遇到的问题的更深入探讨:Can items in PHP associative arrays not be accessed numerically (i.e. by index)?

根据 W3School,:

In PHP, there are three kind of arrays:

  • Numeric array - An array with a numeric index
  • Associative array - An array where each ID key is associated with a value
  • Multidimensional array - An array containing one or more arrays

但这准确吗?数组中的每个元素都可以分配一个索引或一个字符串作为键 - 那么当两者混合在同一个数组中时会发生什么?

$myArray[0] = 'value1';
$myArray['one'] = 'value2';

最佳答案

PHP 中的所有数组都是相同的;它们被实现为将键与值相关联的 HashMap ,无论键是什么类型。

Manual :

The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.

但是,如果一个数组同时具有数字和非数字索引,我仍将其称为关联数组。 “联想”的意义依然存在。

Wikipedia :

An associative array is an abstract data type composed of a collection of unique keys and a collection of values, where each key is associated with one value (or set of values).

...

From the perspective of a computer programmer, an associative array can be viewed as a generalization of an array. While a regular array maps an integer key (index) to a value of arbitrary data type, an associative array's keys can also be arbitrarily typed. In some programming languages, such as Python, the keys of an associative array do not even need to be of the same type.

对于最后一句话,这同样适用于 PHP,如您的示例所示。

关于php - PHP 中的数值数组和关联数组是两种不同的东西吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5931206/

相关文章:

javascript - 如何在ajax代码中访问javascript变量值

php - 在 PHP 中,单个与号 ('&' ) 运算符有什么作用?

php - Laravel Eloquent orWhere 查询

php - 如何在不减慢响应速度的情况下调用微服务?

arrays - Perl:取消引用哈希的哈希

php - 如何以分页方式从 YouTube 获取用户视频

javascript - 使用javascript数组时表格内容不显示?

java - 数组打印出零

java - 如何从数组中取回分配的变量?

javascript - 在动画 Google 条形图标签中使用数组索引/变量