1

I'm trying to create an associative array like this:

$key = '0'
$arr = array((string)$key=>$value);

Later, checking is_string(array_keys($arr)[0]) returns false.

The casting didn't help, using " instead of ' didn't help.

Am I doing something wrong, or is there another way around this, or is it impossible to have a numeric string array key?

2
  • Did you unintentionally leave out the semicolon after your first line? Commented Dec 22, 2009 at 19:14
  • Your question just made me wish that PHP supported accessing array members on returned values (e.g. array_keys($foo)[$bar]). Darn... Commented Dec 22, 2009 at 19:49

4 Answers 4

4

In PHP, strings are converted to numbers when used as index, if they are purely numeric. When assigning it as an array key, it is converted to an integer, and same on access, you can use $arr['0'] to access the key 0.

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

4 Comments

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").
Just edited my answer. My mind was wandering when I wrote "when assigned to a variable". I meant "when used as index".
I know I can still access it using a string, but I specifically wanted to check the type of the key for number vs string.
Well the type is still integer, as long as the string itself is an integer.
2

PHP handles indexes of arrays in a bit more special way than just assigning to variables. Rules are clearly written in manual. Here is excerpt regarding your question.

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"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.

Quote from http://php.net/manual/en/language.types.array.php

Comments

1

Set as Integer, but Accessible as String...

It appears that the keys will be assined the type of "integer" unless something about their value prevents the assignment. You are able to access them as strings, as I demonstrate with the gettype() line.

$array = array("0" => "Jonathan", "1" => "Sampson");
$keys  = array_keys($array);
print gettype((string)$keys[0]); // string

Comments

0

when assigning values to a variable that could possibly be interpreted as multiple different types NEVER rely on them to actually be a specific type.

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.