PHP Array Key encoding?

前端 未结 5 1201
野的像风
野的像风 2020-12-19 13:49

I use a encoded string as a key in array, and also uses the same string as a value in the array, like below code indicates:

$string = \'something in some enc         


        
相关标签:
5条回答
  • 2020-12-19 14:03

    I don't know if you can encode correctly string to use them as keys in an array, but even if it is possible to use such variables names :

    • $élement = 'foo';
    • $garçon = 'bar';

    (note the ç and the é)

    It is not recommended. You should not rely on this.

    You would probably map with current english name or use indexes.

    For utf8 encoding, take a look at the php manual.

    0 讨论(0)
  • 2020-12-19 14:07

    I tried in Japanese (as is what I can test):

    $test["要"]["name"] = "要";
    print_r($test);
    

    And the result went fine, as expected. I'm using UTF-8 for everything. I'm not sure if its a problem with your encoding settings (in php.ini) or the encoding you are using. if that is a problem, why don't you try to encode it with base64? (or other Ascii encoder). That way would be something like:

    $test["6KaB"]["name"] = "要";
    

    I'm not sure what is your goal, so let me know if it was useful.

    0 讨论(0)
  • 2020-12-19 14:12

    Are you viewing it through your browser? Then you need to specify the encoding:

    header('Content-Type: text/plain; charset=UTF-8'); // or BIG5, or whatever

    Are you viewing it in your terminal? Make sure your terminal settings are set to that same encoding.

    0 讨论(0)
  • 2020-12-19 14:14

    Just tried to enforce a collision, but it does not happen.

    PHP Version 5.3.6 (Mac OS 10.7.5)

        $test["要"] = "要";
    
        for ($i=0;$i<5000000;$i++) {
            $key = "";
            $num = $i;
            while ($num != 0) {
                $ascii = $num % 256;
                $num = floor($num / 256);
                $key .= chr($ascii);
            }
    
            $test[$key] = 'boom';
            if ($test["要"] != 'boom') {
                unset($test[$key]);
            }   
        }
    
        print_r($test);
    

    outputs:

        Array ( [要] => 要 )
    

    no collision.

    0 讨论(0)
  • 2020-12-19 14:24

    A key is of type integer or string.

    To quote the manual

    A string is series of characters. Before PHP 6, a character is the same as a byte. That is, there are exactly 256 different characters possible. This also implies that PHP has no native support of Unicode. See utf8_encode() and utf8_decode() for some basic Unicode functionality.

    So it makes sense in your case to encode the string used as key (or only the key, depends on what you will do): utf8_encode()

    0 讨论(0)
提交回复
热议问题