PHP useless indexes

17 11 2006

There’s something terribly wrong in the way PHP parses its input. Look at this simple piece of code:


In any decent language you’d expect this expression to return 1. But not in PHP:

Parse error: syntax error, unexpected ‘[‘

Only solution seems to be to use some temporary variable or function to get a value from newly created array in the same expression.

function get($a, $n) { return $a[$n]; }
echo get(array(1, 2, 3), 0); // => 1

It hurts most when you work with functions that return arrays of values. You can’t write:
localtime()[2] to get current hour, you can’t write:
stat('some_path')[7] to get size of file or:
split(':', 'root:x:0:0:root:/root:/bin/bash')[6] to get shell used by root.

And to get things worse, string indexes behave the same way…



7 responses

18 11 2006

foo()[12] is planed, there is discussions (in the last 1-2 weeks) to support this syntax in the next PHP releases (not sure if it will be 5.x or 6+).

About the first example, it is a declaration/initialization, it makes little sense to use such syntax here. You already know the common syntax:

$a = array(1,2,3); echo $a[0];

Not enough to say that indeces are useless in php, even if I would like a smaller syntax to use arrays, a la C [0,1,3] wihtout the array keyword. But this post is maybe a rant, so ;-)

18 11 2006

It makes perfect sense to use index with array declaration. Imagine:

$message = intval($_REQUEST[‘message’]);
echo array(“Hello”, “Hi”, “Good morning”)[$message];

Where $message is in range 1 to 3.

Can you point some links to the discussion on this topic (probably from php-devel)?

19 11 2006

Ok, it can make sense here, but I find this syntax confusing and unclean (it is a taste matter > not objective). I find the following one nicer:

$choices = array(”Hello”, “Hi”, “Good morning”);

$message = (int)$_REQUEST[’message’];
echo $choices[$message]; // isset/count sanity check ;)

For three reasons:
– declare/init an array this way allows me to use some cache
function smoothly, if the data comes from an external
source (like $choices = apc_fetch(…);).
– it is more readable (taste :)
– in this example, you have to test the index anyway (GET message=12?).

“Can you point some links to the discussion on this topic (probably from php-devel)?”

Here you go (feel free to revive it, or I will do for 6.x or 5.3): and followers

or from google:

20 11 2006

You’re right that it’s a matter of taste. You know, what I really would like to say (and what I mean by writing this code) is:

# print first element from given set
print 1.from [“Hello”, “Hi”, “Good morning”]

which BTW is a proper Ruby code with an extra definition below:

class Integer
def from enum self-1

In PHP numbers (and arrays as well) don’t have methods, so I have to accept less beautiful solution. Still, in some cases (more or less frequent, depending on what you do), making a temporary variable for that kind of simple task is a serious overhead and clutters the code.

Going back to the original post, what struck me most was that PHP said it was a *parser* error. PHP seems to be quite dynamic with its inherited perlish weak typing culture, so it looks really strange that in “foo()[bar]” situation PHP says “No, I won’t even compile it, as it doesn’t look right”. Hell, PHP converts booleans, integers and strings without a word during run time, so it’s really a surprise it doesn’t even want to look at the foo() returning type, before it would say that index operator has been used on wrong type of variable. Having this kind of parsing quirks makes the whole language incoherent, what effectively makes programming in it harder.

20 11 2006

Yes, it is a parser error, simply because a [] after a ) is not supported, nothing uses it. It cannot be a runtime error. When it will support this syntax, it will raise runtime warnings when you try to use [] on a non array.

But PHP being loosely typed is not the point here and it is coherent with any other unsupported syntax raises a parser error.

Having scalars as scalar is in my opinion a good thing. But that’s another discussion :)

22 11 2006

Just a note, mousebender, PHP generally starts array indexes at 0 and not 1.

22 11 2006

Oh, reeeaaally? :)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: