Search code examples
phparraystype-conversionarray-multisort

array_multisort Converts string index into an integer index


I have two arrays:

 $info = array();
 $submitted = array();

I declared an assignment below:

 $info['idnumber'] = 10066;
 $submitted[$info['idnumber']] = 'Wow';

 array_multisort($submitted); 

After doing so, displayed $submitted array.

 foreach($submitted as $key => $row){
      echo $key;
 }

Why does it display 0 instead of 10066? I tried tweaking my code to:

$info['idnumber'] = 10066;
$submitted[(string)$info['idnumber']] = 'Wow';

or

$info['idnumber'] = 10066;
$submitted[strval($info['idnumber'])] = 'Wow';

Still it displays 0. What shall I do to display 10066 as the index of the $submitted array?

Update:

I found out it's a known bug of array_multisort, but still it has no solutions. Any idea how to fix ]it?


Solution

  • As you pointed out it is a known behaviour.

    The solution was proposed in the discussion

    For the moment I'm going to say prefix all your array keys with an extra 0 (or any non-numeric) to force their casting as strings.

    When you try to cast integer into string like this:

    (string)$info['idnumber']
    

    you still get the integer, because you have a valid number as a string.

    So you need to have a string as with some prefix. Prefix can be a 0 or any other non-numeric character. like an i

    $info['idnumber'] = '010066';
    

    Or

    $info['idnumber'] = 'i00066';
    

    This will return the exact index.