PHP 关联数组 - 如何将整数视为字符串
我有一个简单的关联数组。
$a = array("a"=>"b", "c"=>"d");
我想检查数组中是否存在键“1”,例如
isset($a["1"]);
这个字符串被视为整数,那么
echo $a["1"]; //prints "d"
如何让它将其视为字符串?
我不想使用 array_key_exists 或 in_array 因为我的基准测试显示 isset 会快得多。
I have a simple associative array.
$a = array("a"=>"b", "c"=>"d");
I want to check if the key "1" exists in the array, e.g.
isset($a["1"]);
This string is being treated as an integer, so that
echo $a["1"]; //prints "d"
How do I get it to treat it as a string?
I don't want to use array_key_exists or in_array because my benchmarking shows isset will be a lot faster.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看来你不能做你想做的事。来自 http://us.php.net/manual/en/language。 types.array.php:
您可能必须使用 Fosco 的建议,为所有键添加前缀。如果您在每个键上使用相同的前缀,那么您是否正在解析可能包含单词和数字的文本并不重要 - 无论如何,在所有内容上放置相同的前缀。
It doesn't appear that you can do what you want to do. from http://us.php.net/manual/en/language.types.array.php:
You'll probably have to use Fosco's suggestion of prefixing all your keys with something. If you use the same prefix on every key, then it doesn't matter if you're parsing a text that might have words and numbers - put the same prefix on everything regardless.
伊塞特($a["1"]) |伊塞特($a[1])?
或者只是 isset($a[1])
甚至 isset($a[intval(1)]) 1000% 确定。
isset($a["1"]) | isset($a[1]) ?
Or just isset($a[1])
Or even isset($a[intval(1)]) to be 1000% sure.
如果 echo $a['1'] 打印 d,那么您的数组的元素比您想象的要多。
请参阅 var_dump($a) 和 print_r($a) 函数来帮助您调试代码。
if echo $a['1'] prints d, then your array has more elements than you realize.
see var_dump($a) and print_r($a) functions to help you debug your code.