0

Possible Duplicate:
PHP String in Array Only Returns First Character

I've got following problem. When I run script below I got string(1) "F" as an output. How is that possible? No error, notice displayed.. nothing. Key whatever doesn't exist in $c. Can you explain that?

   <?php
   $c = 'FEEDBACK_REGISTER_ACTIVATION_COMPLETED_MSG';
   var_dump ($c['whatever']);
   ?>

I'm having this issue on PHP 5.3.3. (LINUX)

Community
  • 1
  • 1
basstradamus
  • 123
  • 1
  • 10

2 Answers2

4

PHP lets you index on strings:

$str = "Hello, world!";
echo $str[0]; // H
echo $str[3]; // l

PHP also converts strings to integers implicitly, but when it fails, uses zero:

$str = "1";
echo $str + 1; // 2
$str = "invalid";
echo $str + 1; // 1

So what it's trying to do is index on the string, but the index is not an integer, so it tries to convert the string to an integer, yielding zero, and then it's accessing the first character of the string, which happens to be F.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • Why is it trying to convert "whatever" to integer? What's the idea behind this? – basstradamus Oct 15 '11 at 07:08
  • @basstradamus: I assume the PHP developers did this because if you have a string representing a number from, say, `$_GET`, and you want to add a number to it, many beginners would expect it to work without having to convert between types. Here is [the PHP documentation on it](http://us2.php.net/manual/en/language.types.string.php#language.types.string.conversion). – icktoofay Oct 15 '11 at 07:12
  • In other words when variable is not an array but string, any access to it by associative key will result of converting key to the integer type. This is quite important conclusion because isset($c['whatever']) will return TRUE! array_key_exists is a must here. Thanks for a hint icktoofay. – basstradamus Oct 15 '11 at 07:13
0

Through Magic type casting of PHP when an associative array can not find the index, index itself is converted to int 0 and hence it is like if

$sample = 'Sample';

$sample['anystring'] = $sample[0];

so if o/p is 'S';

Rajan Rawal
  • 6,171
  • 6
  • 40
  • 62