Page 1 of 1

Anyone else find it weird we use $foo[] = 'bar'?

Posted: Fri Apr 18, 2008 8:54 am
by Chris Corbyn
It strikes me as odd that even though $foo[] isn't a symbol which can be referenced, we still use it as if it is when assigning to an array.

Code: Select all

$foo[] = 'bar';
It seems to be more like []= should be considered the "array push" operator.

Code: Select all

$foo []= 'bar';
$foo is an array. $foo[] is not an array element. []= together form an operator; yet we never write it that way :?

(I'm thinking too much again!)

Re: Anyone else find it weird we use $foo[] = 'bar'?

Posted: Fri Apr 18, 2008 9:31 am
by dbevfat
Interesting thought, although I don't see it that way. To me, the $a[] is just a shortcut for push in a similar way that javascript allows you to declare an empty array: var a = [];.

Re: Anyone else find it weird we use $foo[] = 'bar'?

Posted: Fri Apr 18, 2008 12:11 pm
by Christopher
$foo[] shows how being human is often (but not always) better than being consistent. Sure you could have []= or [= or ]= operators. But since $foo[$i] is the array syntax, and for the parser $foo[ says foo is an array var, the syntax makes sense. Have you every heard of a PHP programmer who had trouble with the concept once they knew what $foo[] does?

Re: Anyone else find it weird we use $foo[] = 'bar'?

Posted: Sat Apr 19, 2008 1:08 am
by Mordred
Not weird, but with a room for thought certainly. PHP does think it's an "empty index" instead of "array push" operator:

Code: Select all

var_dump(token_get_all('<?php $a[]=5; ?>'));
It will accept either style of whitespace (whereas the assignment operators require the = to be adjacent), so it's up to you how to write it and think of it.

How about this:
$a = $foo["bar"]; //asignment
$b =[] $foo; //array pop operator

It should be possible to do this in Io (I think)

Re: Anyone else find it weird we use $foo[] = 'bar'?

Posted: Sat Apr 19, 2008 9:56 am
by Kieran Huggins
Ruby uses << as it's array push operator, which I sort of dig... but I've been caught a few times trying to use arrays "PHP-style" in ruby. I wonder if it's habit talking or a more natural design. I guess time will tell.

I do love Javascript's object notation though, where empty arrays and objects are [] and {} respectively. Totally compact and easy to read!

Re: Anyone else find it weird we use $foo[] = 'bar'?

Posted: Sun Apr 20, 2008 6:21 am
by Maugrim_The_Reaper
Chris, you think too much. Just confirming your worst nightmare ;)

I think the operator approach is difficult to select from all the alternatives. I usually find Ruby's << hard to read TBH, whereas [] as used to set an array index is more intuitive. Well, for me anyhow...