1

This is just a question of curiosity... I'm wondering if accessing function returned arrays in this method is valid. In this example, I'm using the pathinfo() resulting array.

pathinfo($file)['dirname'];

Or, is it required to set pathinfo() to a variable first and then access it. (The classic method):

$info = pathinfo($file);
$info['dirname'];

I know the classic method is valid, however i'm just curious if the first method is valid too. I've tested it with the latest version of WAMP, and it worked, however Dreamweaver CS5 calls it a syntax error.

2
  • 1
    They're both valid (meaning they will work) in PHP 5.4. In PHP < 5.4, only the second is valid. However, neither is acceptable, since you're not using quotes around your array key like you should. PHP is just (sadly) lenient enough to convert that to a string for you (IF the constant doesn't exist) Commented Mar 7, 2013 at 13:52
  • I forgot the quotes, i've edited to fix. Commented Mar 7, 2013 at 13:57

2 Answers 2

1

PHP 5.4+ supports pathinfo($file)['dirname'];

It is called as array dereferencing

Ref: http://www.schlueters.de/blog/archives/138-Features-in-PHP-trunk-Array-dereferencing.html

Ref: http://php.net/manual/en/language.types.array.php

and less than 5.4

$info = pathinfo($file);
$info['dirname'];
Sign up to request clarification or add additional context in comments.

4 Comments

@ColinMorelli I edited his answer and added quotes, however it may theoretically be that there was define('dirname', 5) or similar earlier in the code, in which case the quotes should not be added.
Thanks for your answer. I was hoping it would be an earlier version, because my production server is 5.3.1.
@AleksG And, given the code sample above, that would be an invalid assumption to make. Because the likelihood is that there's not. Besides, it doesn't hurt to add them and indicate why (that way you leave the decision up to the asker).
@Johnno13 : then you need to use second mehtod
0

Since PHP 5.4 it's possible to do exactly that:

http://php.net/manual/en/language.types.array.php#example-88

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.