tags:

views:

75

answers:

4

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?

+4  A: 

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.

Tor Valamo
Do you have a link to the docs for that ?
Wookai
http://php.net/manual/en/language.types.array.phpA 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").
Derek Illchuk
Just edited my answer. My mind was wandering when I wrote "when assigned to a variable". I meant "when used as index".
Tor Valamo
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.
Ed Marty
Well the type is still integer, as long as the string itself is an integer.
Tor Valamo
+2  A: 

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

Julian Davchev
+1  A: 

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
Jonathan Sampson
A: 

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.

Techpriester