2

How can I transform the keys of the following array to strings in PHP?

$array = array(
    0 => 'a',
    1 => 'b'
);

Expected:

$array = array(
    '0' => 'a',
    '1' => 'b'
);

Basically I need to change a normal array to an associative array but the keys must not be integers, because of a bug in ZF1..

Update:

The bug in ZF1 is not a bug, but a reserved word; please see the other question Zend multiCheckbox default values bug for explanation why I thought I needed this one.

Community
  • 1
  • 1
Daniel W.
  • 31,164
  • 13
  • 93
  • 151
  • You can't. PHP will always treat numeric string values as integers and make conversion to numeric index. that being said, what is the difference? If you know the key you need for lookup, why do you care that it is integer? – Mike Brant May 05 '14 at 16:24
  • I don't care, but Zend Framework 1 cares... see http://stackoverflow.com/questions/23476847/zend-multicheckbox-default-values-bug. If it doesn't work otherwise, I need to prepend a string like `flag-2`, `flag-1024` to all my bit flags...... – Daniel W. May 05 '14 at 16:25

1 Answers1

6

This is not possible.

PHP will internally detect that it's a number (even in quotes) and convert it back. If you notice: the original array and the end one are identical. That's because PHP's automatically casting it for you.

The only way to prevent that is to not use numbers. You could prefix the numbers:

$a = [
    "_0" => "a",
    "_1" => "b",
]

But in general, you don't want to do that. And as you said, it's not even required by the code you thought it was.

And if you are wondering why it casts for you. I have one response. Because:

Because PHP

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
ircmaxell
  • 163,128
  • 34
  • 264
  • 314
  • 7
    +1 for bouncing elephpant – salathe May 05 '14 at 18:02
  • 1
    He-he. Since elephant is here, so [here we are](http://3v4l.org/fTJF2): `$a = new StdClass(); $a->{'0'} = 'a'; $a->{'1'} = 'a'; $a = (array)$a;` Why? [Because PHP](http://i.imgur.com/rD2MZjo.gif) :p – Alma Do May 05 '14 at 18:09
  • They "fixed" that behavior in PHP 8. Now it always false converts strings into integers. I'd bug report it if I thought the person receiving that report was sane. – John Feb 11 '23 at 04:37