PHP是否处理数字索引的数组不同的(内部)? [英] Does PHP handle numerically-indexed arrays differently (internally)?

查看:124
本文介绍了PHP是否处理数字索引的数组不同的(内部)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

...不是关联数组?

做关联数组需要更多的内存还是什么?

  $ ARR =阵列(1,1,1);
$ ARR [10] = 1;
$常用3 [] = 1; //< - 指数为11;请问阵列成为联想在这里?


解决方案

在短期PHP不具有非关联数组。

@Sectus发布了一个很好的答案PHP数组的底层实现重。它往往是有益的理解发生了什么事情引擎盖下。但无论他们的底层实现,PHP阵列的暴露的PHP的开发作为关联键(即关联数组)值的有序映射。始终。

PHP:数组 - 手动


  

在PHP中的数组实际上是一个有序图。图是一种把值keys的类型。



  

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



  

键可以是整数或字符串。


这数组索引数值由功能整数键自动递增为方便起见引起的,在没有密钥明确指定该案件的误解。

但请注意,即使所有按键都是整数,有一个在PHP不能保证一个项目存在于如$改编[0],这在我所知的是,给定任何其他语言确实的使用索引阵列(即,假定索引数组包含至少一种元素,并且是基于0的)。

这不是一个简单的区分。谁靠PHP数组表现得像索引数组,恕我直言,程序员的没有思想的潜在后果或差的理解* 的可能设置自己(或未来的维护者)为怪/意外行为。

*我这个资格,因为有明显凡的通知的决定采取指数般的便利优势/阵列周围PHP语言的功能,可以提供利益的案件。

...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?

解决方案

In short PHP does not have non-associative arrays.

@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.

From PHP:Arrays - Manual

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

and

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

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).

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.

*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是否处理数字索引的数组不同的(内部)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆