Page 1 of 1

Strange string -> array behaviour

Posted: Fri Oct 08, 2010 6:12 am
by ruflin
Hi

I'm using PHP 5.3.3 on Mac OS X. Today I had some strange behaviour with a string that I didn't expect. Now I'm curious if this is the expected behaviour, and if yes, why.

I'm using the following code:

Code: Select all

<?php

$input = 'test';

var_dump(is_string($input));
var_dump(is_array($input));

var_dump($input);
var_dump(isset($input['value']));
echo $input['value'];
var_dump($input);

echo $input;
The output of this code is
[syntax]
boolean true
boolean false
string 'test' (length=4)
boolean true
t
string 'test' (length=4)
test

[/syntax]

First I expected, that isset($input['value'] is wrong, because it's a string. Second I'm suprised, that what ever I insert for 'value' I received the first character of the string and no error. Why is this the case?

Re: Strange string -> array behaviour

Posted: Fri Oct 08, 2010 7:05 am
by loCode
Because in PHP strings are actually arrays.

Re: Strange string -> array behaviour

Posted: Fri Oct 08, 2010 7:24 am
by ruflin
Yes, but I would expect that $input[0] works, but $input['keyname'] throws an error when the key is not set, like this is the case with "normal" arrays. So why is $input['anykey'] returning the first character?

Re: Strange string -> array behaviour

Posted: Fri Oct 08, 2010 7:33 am
by requinix
Strings are not arrays. They are strings. PHP supports character access by using the same symbols and syntax you would use with arrays, but that's the only similarity. There is no relationship between the two.

So it's not an issue of "whether the key exists". If you give an offset, PHP will convert it to a number if it isn't one already. The string "value" becomes 0 and thus it finds the first character. If you give a string like "1a2b" you'll get 1, and with "987zyx" you'll get 987.

Re: Strange string -> array behaviour

Posted: Fri Oct 08, 2010 7:36 am
by Weirdan
First, PHP strings are not PHP arrays. You just can access individual bytes (not characters) using array-like notation.

Second, PHP is dynamically typed language, thus it performs automatic type conversion in so many places, and string offset is just another one. What it actually does in your case is $input[(int) 'value'] which translates to $input[0].

Re: Strange string -> array behaviour

Posted: Fri Oct 08, 2010 8:39 am
by ruflin
@Weirdan, @tasairis: Really interesting. Didn't know that, but now it makes sense. So also isset($input['key']) is converted to 0. I added now an additional check in my code if(is_array($input) && isset($input['key'])) and now it works (the value can be a string or array).

Thanks for your help.