tags:

views:

161

answers:

3

Hello,

I have an array in PHP which looks like that:

$test = array('3' => 5);

How could I replace the stringed array key 3? I tried:

$test['3'] = "New value"

but it don't work, it look like that after that:

array('3' => 5, 3 => "New value")

PHP version: 5.2.11

+4  A: 

Works great for me

$ php -r '$foo = array("3" => 5); $foo["3"] = 6; print_r($foo);'
Array
(
    [3] => 6
)
Trey
Which PHP version do you have? I added mine in the question...
Poru
$ php -vPHP 5.3.1 (cli) (built: Feb 11 2010 02:32:22) Copyright (c) 1997-2009 The PHP GroupZend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies
Trey
and on another machine:$ php -vPHP 5.2.11 with Suhosin-Patch 0.9.7 (cli) (built: Dec 11 2009 16:30:44) Copyright (c) 1997-2009 The PHP GroupZend Engine v2.2.0, Copyright (c) 1998-2009 Zend Technologies
Trey
works here even on my old mac internal php version.PHP 5.2.11 (cli) (built: Dec 14 2009 19:23:40) Copyright (c) 1997-2009 The PHP GroupZend Engine v2.2.0, Copyright (c) 1998-2009 Zend Technologies
Tobias
Works on 5.3.1 on Windows XP too
nickf
+2  A: 

The most possible way you can get the numerical index represented by string is when you convert object with numeric property name to array.

More detailed this covered here

zerkms
Okay, I casted the "source array" to an object, now it works!
Poru
+2  A: 

The first is actually creating a numerically indexed array key, the second a string key. You can use type casting to force consistent behavior.

$test = array((string) '3' => 5);
$test[(string) '3'] = "New value";

Update, these behave identically for me on PHP Version 5.2.13:

$test = array('3' => 5);
echo '<pre>'.print_r($test,true).'</pre>';
$test['3'] = "New value";
echo '<pre>'.print_r($test,true).'</pre>';

$test = array((string) '3' => 5);
echo '<pre>'.print_r($test,true).'</pre>';
$test[(string) '3'] = "New value";
echo '<pre>'.print_r($test,true).'</pre>';
Sonny
casting string to string? ;-)
zerkms
this might be a silly question, but isn't `'3'` already a string?
nickf
@nickf - it absolutely is. And my mind is going round in circles with this question. What could it possibly mean? my best guess is the code in the question is *not* what was tested.
karim79
Normally I expect people to leave a comment when they downvote an answer, but for this one, I'm left pondering why you'd upvote it? All that it says is a string is the same after you cast it to a string.
nickf
I was assuming that he had a variable that had the value of '3' in it, and was getting odd behavior for that reason. The accepted answer is a much different situation. I wish the OP had given a better code example. I don't know who voted me up.
Sonny