"z", "a" => "a", "b" => "b"); f-6ren">
gpt4 book ai didi

php - PHP 中是否保证关联数组的顺序?

转载 作者:可可西里 更新时间:2023-10-31 22:09:02 25 4
gpt4 key购买 nike

当我在 php 中对关联数组执行 foreach 循环时,它的执行顺序就是它定义的顺序。

例如:

$arr = array("z" => "z", "a" => "a", "b" => "b");

foreach($arr as $key => val)
print("$key: $val\n");

输出:

z: z
a: a
b: b

鉴于

$arr = array("a" => "a", "b" => "b", "z" => "z");

输出:

a: a
b: b
z: z

那么我的问题是:这种行为是在规范级别定义的吗?我可以合理地确定这种行为在未来的 PHP 版本中不会改变吗?

最佳答案

来自PHP Manual

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.

Arrays are ordered. The order can be changed using various sorting functions.

因此您可以确定(至少目前)订单将得到维持。如果此行为发生变化,我会感到非常惊讶,因为它已明确说明,因此将会有大量代码依赖它。

关于php - PHP 中是否保证关联数组的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/950975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com