Hi Francois,

On Tue, Feb 9, 2016 at 12:09 AM, François Laupretre <franc...@php.net> wrote:
> Slightly off-topic but, as I was looking for the way to add support for
> '$str[]=' assignments, I found something strange.
>
> Just for curiosity, does someone know a reason for this :
>
> $str = "abc";
> $str[1]="z";
> var_dump($str); // -> string(3) "zbc" -> Expected
>
> $str = ""; // Empty string
> $str[1]="z";
> var_dump($str); // -> array(1) { [0]=>string(1) "z" } -> !!!
>
> The input string is converted to an array if it is empty. This becomes still
> funnier with :
>
> $str="a";
> $str[] = 'z'; // -> Fatal error : [] operator not supported for strings
>
> $str="";
> $str[] = 'z'; // -> OK -> $str gets array(1) { [0]=>string(1) "z" }
>
> Thoughts ?

PHP should raise E_WARNING errors for them as other scalar, IMO.

php > $v=1;
php > $v[] = 'z';
PHP Warning:  Cannot use a scalar value as an array in php shell code on line 1

php > $v=TRUE;
php > $v[] = 'z';
PHP Warning:  Cannot use a scalar value as an array in php shell code on line 1

It seems "" is treated just like NULL/FALSE

php > $v=null;
php > $v[] = 'z';
php > var_dump($v);
array(1) {
  [0]=>
  string(1) "z"
}
php > $v=false;
php > $v[] = 'z';
php > var_dump($v);
array(1) {
  [0]=>
  string(1) "z"
}

NULL may become any type of variables, but empty string and FALSE should
behave like 'scalar' variable. This could be largest BC of this RFC,
but it's consistent with int variable.

php > $v=0;
php > $v[] = 'z';

Warning: Cannot use a scalar value as an array in php shell code on line 1


BTW, what would happen with $var{} = 'str'?

php > $v='abc';
php > $v{} = 'str';
PHP Parse error:  syntax error, unexpected '}' in php shell code on line 1

Currently, it's not allowed. It may behave like $v .= 'str'. I'm not
sure if PHP should. It looks consistent syntax with array.
i.e. "$v[] = $val" adds $val as last element.

Behavior regarding array. (a bit off topic, but error level should
match with new string '{}' errors.)

php > error_reporting(-1);
php > $v=array();
php > $v .= 'abc';

Notice: Array to string conversion in php shell code on line 1
php > var_dump($v);
string(8) "Arrayabc"

This insane string assignment raises E_NOTICE. PHP may be better to
raise E_WARNING for this kind of invalid assignments just like

php > $v=1;
php > $v[] = 'z';
PHP Warning:  Cannot use a scalar value as an array in php shell code on line

Regards,

--
Yasuo Ohgaki
yohg...@ohgaki.net

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to