Home > php教程 > php手册 > PHP数组关于数字键名的问题

PHP数组关于数字键名的问题

WBOY
Release: 2016-06-21 08:48:07
Original
1699 people have browsed it

以下是对PHP数组数字键名的几点总结:

键名长度只能在 int 长度范围内,超过int 范围后将会出现覆盖等混乱情况

在键名长度为 int 范围内存取值时,PHP会强制将数字键名转换为 int 数值型

数字键名长度大于19位时,将变成 0


键名正常长度时,字符串或数值类型一样

$i = 126545165;
$arr['126545165'] = 'abc';
$arr[126545165] = 'uio';
var_dump($arr);
echo &#39;<br/>&#39;;
var_dump(isset($arr[$i]));
Copy after login




长度超过整型时,键名混乱<喎?http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+PHByZSBjbGFzcz0="brush:java;">$i = 12312312312312; $arr['1000000000147483649'] = 'abc'; $arr[1000000000147483649] = 'uio'; var_dump($arr); echo '
'; var_dump(isset($arr[$i]));





长度超过20位时,键名将变成 0

$i = 123123123123123123123123123123;
var_dump($i);
echo &#39;<br/>&#39;;
$arr[123123123123123123123123123123] = &#39;abc&#39;;
$arr[strval(123123123123123123123123123123)] = &#39;abc&#39;;
var_dump($arr);
echo &#39;<br/>&#39;;
var_dump(isset($arr[$i]));
echo &#39;<br/>&#39;;
var_dump(isset($arr[strval($i)]));
echo &#39;<br/>&#39;;
var_dump(array_keys($arr));
Copy after login




将变量直接作为键名存取,结果又有不同

$i = 123123123123123;
var_dump($i);
echo &#39;<br/>&#39;;
$arr[$i] = &#39;abc&#39;;
$arr[strval($i)] = &#39;abc&#39;;
var_dump($arr);
echo &#39;<br/>&#39;;
var_dump(isset($arr[$i]));
echo &#39;<br/>&#39;;
var_dump(isset($arr[strval($i)]));
echo &#39;<br/>&#39;;
var_dump(array_keys($arr));
Copy after login


从上面的几种测试来看:

如果键名为数字,且范围在 int 以内,字符串或者 int 不会对存取有什么影响

如果长度大于 int 时会自动转化为 float ,再转换进行存取出现各种混乱情况,甚至直接变成 0,所以最好是统一转换为 string 类型


$i = 123123123123123123123123123123;
$j = &#39;123123123123123123123123123123&#39;;
$arr1[strval($i)] = &#39;abc&#39;;
$arr2[$j] = &#39;abc&#39;;
var_dump($arr1);
echo &#39;<br/>&#39;;
var_dump($arr2);
Copy after login




所以在动态操作 PHP 数组时,如果不能确定键名是否会出现数字或者长度大于 int ,则统一将键名 strval 转换为 字符串来操作最为稳妥



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template