PHP associative arrays - how to treat integer as string

喜欢而已 提交于 2020-01-03 09:12:09

问题


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.


回答1:


It doesn't appear that you can do what you want to do. from http://us.php.net/manual/en/language.types.array.php:

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08").

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.




回答2:


isset($a["1"]) | isset($a[1]) ?

Or just isset($a[1])

Or even isset($a[intval(1)]) to be 1000% sure.




回答3:


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.



来源:https://stackoverflow.com/questions/4637680/php-associative-arrays-how-to-treat-integer-as-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!