...than associative arrays?

...比关联数组?

Do associative arrays take more memory or something?

关联数组会占用更多内存吗?

$arr = array(1, 1, 1);
$arr[10] = 1;
$arr[] = 1; // <- index is 11; does the array become associative here?

4 个解决方案

#1


6

In short PHP does not have non-associative arrays.

简而言之,PHP没有非关联数组。

@Sectus has posted a good answer re the underlying implementation of PHP arrays. It is often beneficial to understand what's going on "under the hood". But regardless of their underlying implementation, PHP arrays are exposed to the PHP developer as an ordered-map of values associated to keys (ie, an associated array). Always.

@Sectus在PHP数组的底层实现上发布了一个很好的答案。了解“引擎盖下”发生了什么通常是有益的。但无论它们的底层实现如何,PHP数组都会作为与键关联的值的有序映射(即关联数组)向PHP开发人员公开。总是。

From PHP:Arrays - Manual

来自PHP:Arrays - Manual

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

PHP中的数组实际上是一个有序的映射。映射是将值与键关联的类型。

and

PHP arrays can contain integer and string keys at the same time as PHP does not distinguish between indexed and associative arrays.

PHP数组可以包含整数和字符串键,因为PHP不区分索引数组和关联数组。

and

The key can either be an integer or a string.

密钥可以是整数或字符串。

The misconception that arrays are numerically indexed is caused by the feature that integer keys are auto-incremented as a matter of convenience, in the case where no key is explicitly specified.

数组被数字索引的误解是由于在没有明确指定密钥的情况下整数键自动递增的特征。

But note, even when all keys are integers, there's no guarantee in PHP that an item exists at eg $arr[0], which to my knowledge is a given in any other language that does use indexed arrays (that is, assuming the indexed array contains at least one element, and is 0-based).

但是请注意,即使所有键都是整数,PHP也无法保证项目存在于例如$ arr [0],据我所知,这是使用索引数组的任何其他语言中给出的(即,假设已编入索引)数组包含至少一个元素,并且基于0)。

This is not a trivial differentiation. IMHO programmers who rely on PHP arrays behaving like indexed array without thought for the potential consequences or understanding of the difference* may be setting themselves (or future maintainers) up for strange/unexpected behaviour.

这不是一个微不足道的区别。依赖于PHP数组的IMHO程序员表现得像索引数组而没有考虑到潜在的后果或对差异的理解*可能会为自己(或未来的维护者)设置奇怪/意外的行为。

*I've qualified this, as there are obviously cases where an informed decision to take advantage of the index-like conveniences/features of the PHP language around arrays can provide benefit.

*我已经对此进行了限定,因为有明显的情况下,利用类似于索引的PHP语言的方便/特性可以提供好处。

更多相关文章

  1. PHP不区分大小写数组搜索函数[duplicate]
  2. 如何找到数组的大小
  3. PHP:将simpleXML对象转换为二维数组
  4. 从JSON字符串/数组中提取第一个图像
  5. 使用包含特定号码的网址重定向到索引
  6. PHP根据数组的值分组
  7. 找出数组中大于或等于N的数
  8. PHP用空格分割文本为数组的方法
  9. 如何使用ChromePhp Logger记录数组

随机推荐

  1. ASP.NET Core 应用程序发布命令实例
  2. 分享在C#中时间戳是怎么转换的?
  3. 如何使用C#来制作扫雷游戏的图文代码教程
  4. winform 信息管理系统图文实例
  5. C#开发中遇到的问题分享
  6. C#如何在图片增加文字的示例代码分享
  7. IdentityServer4 授权配置AllowedScopes
  8. 调用user32.dll显示其他窗口
  9. 关于C#winform如何实现右下角弹出窗口结果
  10. 什么是Less?koala配置及使用