Page 1 of 1
WHy is this valid?
Posted: Fri Dec 19, 2008 6:58 pm
by josh
WHy is this syntactically valid in PHP?
Re: WHy is this valid?
Posted: Fri Dec 19, 2008 7:18 pm
by requinix
Huh. Wow, I learned something today.
If you look at the
manual page you'll see
Syntax "index => values", separated by commas, define index and values. index may be of type string or integer. When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1. Note that when two identical index are defined, the last overwrite the first.
Having a trailing comma after the last defined array entry, while unusual, is a valid syntax.
Let's you have code like
Code: Select all
array(
"First",
"Second",
"Third",
"Fourth",
)
without having to worry about removing that last comma.
Re: WHy is this valid?
Posted: Fri Dec 19, 2008 7:19 pm
by RobertGonzalez
Why would it not be?
An array can contain any value within it. The comma just tells the array you are about to add another member. It is the same as doing...
Code: Select all
<?php
$array = array(
'value1',
null,
false,
);
To PHP, that last comma means nothing until it comes time to add more members to the array.
Re: WHy is this valid?
Posted: Fri Dec 19, 2008 7:43 pm
by josh
Hmm, I would have guessed it "tells" the interpreter to expect another value after the comma, not as an optional delimiter marking the end of the current value. I guess it it makes sense now. I actually discovered it during debugging... I was copying stuff around and then saw it and was like WTF how is this even parsing? lol.. thanks for RTFMing for me.
Re: WHy is this valid?
Posted: Fri Dec 19, 2008 9:56 pm
by Christopher
jshpro2 wrote:
WHy is this syntactically valid in PHP?
PHP is one of the few languages that allow an extra hanging comma at the end of lists. I assume it is because in PHP you generate things like arrays, so itmakes it simpler to just concat every element with a comma at the end.
Re: WHy is this valid?
Posted: Fri Dec 19, 2008 10:28 pm
by John Cartwright
I first came across this phenomena with:
Crazy stuff!

Re: WHy is this valid?
Posted: Sat Dec 20, 2008 6:21 am
by VladSun
I've been using trailing commas for ages
I use a trailing comma in JS too:
[js] this.addEvents({ "updateSuccess" : true, "updateFailure" : true, "dirtyState" : true, });[/js]
Although, it's not right
Warning: trailing comma is not legal in ECMA-262 object initializers
Re: WHy is this valid?
Posted: Sat Dec 20, 2008 6:23 am
by VladSun
Jcart wrote:I first came across this phenomena with:
Crazy stuff!

I prefer:
I do use such loops indeed

For daemonizing scripts and put them into background (mostly Perl) - of course with a call to u/sleep() in it.
Re: WHy is this valid?
Posted: Sat Dec 20, 2008 11:12 am
by mmj
I once tried
wanted to the first element to be empty. Didn't work though, so I set it to null.