0
    $ar['123'] = "test";
    var_dump($ar); // Key is int
    $ar2['123a'] = "test";
    var_dump($ar2); //Key is string

Why is this happening ? Is there a work around ? I want to have a key of numbers as a string not as an integer.

Thnx

Noki
  • 451
  • 3
  • 6

4 Answers4

0

you can use "123" as a number when needed. and also you can substr or strlen "123" as string. php variables are flexible.

Taha Paksu
  • 15,371
  • 2
  • 44
  • 78
0

You don't have to worry about data types in PHP, the conversions are done automatically for you.

Just to give you an example, the following code:

<?php
        if("10" == 10)
        {
                echo "It's equal!";
        }
?>

Will actually output:

It's equal!

You can see it in action here: http://ideone.com/aayLx

Bottom line is: don't worry about it, PHP will treat it as a string when you need it to.

Telmo Marques
  • 5,066
  • 1
  • 24
  • 34
  • Yes i know that, my problem was that i wanted it to be a string cause i am encoding the array to json latter and weird things happen :P – Noki Mar 17 '12 at 02:43
  • Well, weird things shouldn't be happening. Could you be more specific? – Telmo Marques Mar 17 '12 at 02:44
  • 1
    Its ok i found where the problem was. Json had nothing to do with that. I am reversing the array before i encode it but i forgot to set to true the second parameter in order to preserve the keys of the array. – Noki Mar 17 '12 at 02:52
0

You can typecast the key to a string but it will eventually be converted to an integer due to PHP's loose-typing. From the manual http://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").

Xabier Arrabal
  • 180
  • 2
  • 8
0

Strings are automatically casted to integers when the string is an integer. See http://php.net/manual/en/language.types.array.php for more information on this.

To work around this, you must prepend the integer with a 0:

$ar2["0123"] will use '123' as the key
TheOx
  • 2,208
  • 25
  • 28