7

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.

6
  • 3
    .. the easy answer is, don't use string integers for your associate arrays. Add a prefix, or completely change your naming convention. Why create a work-around to accommodate this preventable design choice? Commented Jan 9, 2011 at 4:31
  • I'm parsing words from a text and checking their index, some of those will be numbers, so I have to do it this way. Commented Jan 9, 2011 at 4:34
  • 2
    -1 bogus question, php doesn't behave this way. Commented Jan 9, 2011 at 5:00
  • @chris, what do you mean? Commented Aug 7, 2013 at 15:01
  • @Pacerier echo $a["1"]; doesnt print "d". Commented Aug 8, 2013 at 13:31

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Or just isset($a[1])

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

1 Comment

Other way around, looking for string, not integer
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.