8 ms·
Short array syntax finally in PHP 5.4
- viraptor 15y agoJust looked through the RFCs... and I'm a bit surprised noone proposed unification of types yet. It seems a bit silly that the resources, objects, arrays, strings are different types at the language level. They could throw out / reorganise a lot of the randomly named functions this way. Just add the proper methods to the actual types and sort out the (haystack, needle) order, underscores or lack of them, etc.
- nyordanov 15y agoRight, but wouldn't that make PHP code too good looking? The core devs wouldn't allow it ;) My only wish is that they implement something that evaluates {} to (object)array(). It would come in handy when used with anonymous functions. Anyway, I am pleased with the new syntax, but sadly, I have to use 5.2 as most of the time I'm working on WordPress projects...
- Udo 15y agoThat's great news, finally we can do $a = [1, 2, 3]; and it also will make function calls with named parameters much more readable. Sadly, it will be years before the majority of hosting providers adopt 5.4...
- program 15y agoAlso arrays of arrays have a much more compact syntax: $a = [1 => [4, 5, 6], 2 => [7, 8, 9], 3 => [10, 11, 12]]; $a = array(1 => array(4, 5, 6), 2 => array(7, 8, 9), 3 => array(10, 11, 12));
- nknight 15y agoUh, why wouldn't [[4, 5, 6], [7, 8, 9], [10, 11, 12]] work? I know PHP has a weird history of rebelling against its C-family-syntax heritage, but requiring the syntax in your example would seem specifically calculated just to make developers' lives harder.
- inji 15y agoI think it might? http://svn.php.net/viewvc/php/php-src/branches/PHP_5_4/tests/lang/array_shortcut_005.phpt?view=markup&pathrev=313641 http://svn.php.net/viewvc/php/php-src/branches/PHP_5_4/tests...
- paradoja 15y agoWell, arrays start with index 0, so if the indexes where 1 less it would be the same. Your example would be equivalent to [0 => [4, 5, 6], 1 => [7, 8, 9], 2 => [10, 11, 12]]
- abarrett 15y agoIn addition, you only need to specify the first key to create a one-based array. Indexing will carry on from there. [1 => [4, 5, 6], [7, 8, 9], [10, 11, 12]]
- joelhaasnoot 15y agoYour example would work, but there's a reason you might want different keys. My company's current web app is written in CakePHP, which has a love for arrays. Some of my queries look like this: $booking = $this->Booking->find('first', array('conditions' => array('Booking.booking_id' => $id), 'contain' => array('Review', 'Desk' => array('fields' => array('provider_id', 'category_id'), 'Provider' => array('city', 'name'), 'ProviderCategory' => array('fields' => array('provider_id', 'category_id'), 'DeskCategory' => 'name'))))); It's essentially not readable, but with [] it would work much better, and I still want to give keys to arrays.
- josegonzalez 15y agoAs an FYI, you might want to look into custom find methods if you haven't already: https://github.com/josegonzalez/documentation/blob/master/03-good-cake/01-models.textile https://github.com/josegonzalez/documentation/blob/master/03...
- brendoncrawford 15y ago> Sadly, it will be years before the majority of hosting providers adopt 5.4... With VPS hosting as low as $6/month, what reason is there to continue using shared hosting anyways?
- Udo 15y agoPersonally, I'm quite happy with VPS and would never go back to shared hosting without a good reason. But if you're writing software that is going to be used on lots of "standard hosting" packages you have to take this kind of delay into account.
- barredo 15y agoNow if only when a function returns an array we needn't a variable... function boo(){ return array(1,2,3) } echo boo()[1];
- joelhaasnoot 15y agoEspecially since you can do $a->b->c->d
- nbpoole 15y agohttp://svn.php.net/viewvc?view=revision&revision=300266 http://svn.php.net/viewvc?view=revision&revision=300266 http://www.php.net/archive/2011.php#id2011-06-28-1 http://www.php.net/archive/2011.php#id2011-06-28-1 It's in PHP 5.4 alpha as well ;)
- barredo 15y agoThanks!
- whiskers 15y agoIt's not quite what you're asking for, but there is a way to handle array results from functions where you know the number of elements that will be returned. For example: // explode splits the string on the provided boundary // and returns an array containing each segment. // using list() we can assign the two segments to two // variables within the same statement $size = "1000x1000"; list( $width, $height ) = explode( "x", $size );
- andrewvc 15y agoAh yes, I love nothing more than functions on the left side of assignment. Edit: Yes, it is a special form, but its still irregular, and that makes it shitty.
- abarrett 15y agohttp://www.php.net/manual/en/function.list.php http://www.php.net/manual/en/function.list.php It's a language construct, not a function.
- nbpoole 15y agoWith the removal of bad legacy features like register_globals, magic_quotes_gpc, and safe_mode combined with new features like array de-referencing and traits, I'm really excited for PHP 5.4. :) For anyone who's curious, here's a list of the changes in 5.4 alpha 1: http://www.php.net/releases/NEWS_5_4_0_alpha1.txt http://www.php.net/releases/NEWS_5_4_0_alpha1.txt
- agotterer 15y agoWhat's the release roadmap and dates for 5.4?
- nbpoole 15y agohttps://wiki.php.net/todo/php54 https://wiki.php.net/todo/php54
- gdulli 15y agoMy big complaint about arrays wasn't declaring them. It was the endless array functions you have to use afterwards. array_push array_pop array_slice array_shift array_unshift array_map array_key_exists It kind of feels like they missed the point, saving 5 characters when you declare the array once, ignoring all of the other operations you do afterwards. And this RFC, simple as it is, took 3.5 years to come to fruition.
- ryanb 15y agoagreed. this is one of my pet peeves with PHP also.
- robryan 15y agoHard to say that it is simple unless you know the internals.
- vmind 15y ago2 lines in the parser: http://svn.php.net/viewvc/php/php-src/trunk/Zend/zend_language_parser.y?r1=313094&r2=313641 http://svn.php.net/viewvc/php/php-src/trunk/Zend/zend_langua... The RFC (https://wiki.php.net/rfc/shortsyntaxforarrays https://wiki.php.net/rfc/shortsyntaxforarrays) was actually rejected by the developers, I think it's only really been put in to appease large userland pressure. Find it rather amusing that a 2 change to the parser for an alias would be rejected on 'maintainability' grounds.
- birken 15y agoThe voting results on the RFC page is from 2008 when it was rejected. The recent vote that decided its inclusion was here: https://wiki.php.net/todo/php54/vote https://wiki.php.net/todo/php54/vote. I think it had pretty solid support from core developers as well as userland people this time around.
- zakovyrya 15y agoAnd why should everyone know or care about language internals?
- ck2 15y agoBut PHP isn't a transmitted language like javascript, why even bother? It will only make the parser slower?
- jey 15y agoThey're trying to be nicer to the humans. (Though IMO, any human who wanted to be kind to himself would just not use PHP to begin wtih.)
- ma2rten 15y agoRight now those humans would not choose to start a project in php, but a few years ago there were not too much alternatives. It's not for nothing that the world's second biggest website is written in php.
- deleted 15y ago[deleted]
- code_duck 15y agoDo you mean Facebook? They only use PHP for templating and legacy purposes, as far as I understand. Much of their newer code is written in a variety of languages, including C++, Python and Erlang.
- vmind 15y agoIt's just an additional alias in the grammar, no real measurable slow down given the size of the parser as is.
- swivelmaster 15y agoAny site that needs real speed will be using APC or eAccelerator anyway, so that's not really relevant.
- bluekeybox 15y agoIn the immortal words, I am not even able rightly to apprehend the kind of confusion of ideas that could provoke a question like that. Slower parsing, really? Is that what you are worrying about?
- MattBearman 15y agoThat's good to see, but like many have said, I'd really like to see proper OO stuff like $myArray->pop(); What about short object declaration syntax: $obj = { param:'blah' }; PHP already has stdClass, so I doubt it would take much of a parser change to implement that.
- Tharkun 15y agoStill strikes me as a useless bit of syntactic sugar. Is it really that much work to write array('foo' => 'bar')? As far as I can tell, writing ['foo' => 'bar'] isn't that much shorter in the first place. sigh Can the PHP devs focus on the real problems now? cough Unicode anyone? Ridiculously inconsistent naming of string and array functions? The woefully incomplete and useless STL? The lack of OO in arrays and strings?
- MostAwesomeDude 15y agoHey, I've been complaining about PHP's lack of Unicode support forever. Every time I do, though, an apologist comes out of the woodwork to tell me about the mb_*() functions. Apparently the PHP community is quite comfortable not caring about non-ASCII characters.
- cheald 15y agoI brought down a production site by innocently changing some string ops to mb_* string ops. It turns out that they're so slow as to be useless.
- ars 15y agoI use unicode all the time, and I have not had any trouble. All the php functions are binary safe. If you use utf-8 you won't have any touble. Do you have actual real issues, or do you just like to complain about things you heard other people say?
- nosnih 15y agohttp://www.slideshare.net/andreizm/the-good-the-bad-and-the-ugly-what-happened-to-unicode-and-php-6 http://www.slideshare.net/andreizm/the-good-the-bad-and-the-... Andrei Zmievski has been giving this presentation on what happened to Unicode in PHP. A huge amount of work went into making it happen but it eventually could not continue due to several reasons, including design decisions, lack of contributors & interest in the project.
- mmuro 15y agoAgreed. I don't see how this solves a real problem other than just another way to write the code, which, I guess, is the whole point of this update.
- jrockway 15y agoSo does => quote the lhs, like Perl? Otherwise, what's the point?
- ars 15y agoI take it you don't know anything about PHP?
- snomad 15y agoLooks like they decided NOT to include the scalar type hint. https://wiki.php.net/todo/php54 https://wiki.php.net/todo/php54 Even better would be bool/float/int/string/func ref type hinting...
- thesmartace 15y agoWhile I don't use PHP any more, this is still a massive improvement for those that do. Next on the list: Array and String literals as proper objects!
- snorkel 15y agoMy complaint about arrays in PHP is warnings for reading a array member that may not exist, such as when reading a form input that might not be there. $foo = $_POST["foo"]; Undefined array key! Oh, no! Tragedy! A crime has been committed! Are you kidding? Just set $foo to undefined and let me deal with the consequences, please?
- nbpoole 15y agoThey're notices, not warnings. They can be disabled via a simple call to the error_reporting function. I fundamentally disagree with you though. For me, notices are very useful for identifying typos and other coding mistakes that can lead to incorrect behavior. Consider the following lines of code: $user_info = array( 'id' => 1, 'username' => 'nbpoole', 'is_guess' => false ); if (!$user_info['is_guest']) { echo 'Member stuff'; } When I run that script with error_reporting set to E_ALL, I get an "undefined index" notice pointing me to the line where I do the comparison: at that point, I can track down where in my code I misspelled the word guest. Without the notice, I might not immediately realize that the 'is_guest' index was mis-spelled somewhere.
- kylewpppd 15y agoThis is exactly what PHP does. Yes, it issues you a notice, not a warning, not an exception. And it does not break execution. Just set your error_reporting variable to a lower level, and you won't get the Notice at all.
- code_duck 15y agoYou really wouldn't like Python or even stricter languages such as Scala or java, then. In Python, an attempt to access a nonexistent dictionary key will throw an exception which halts execution if not caught. (similar to calling a nonexistent method or function in PHP, but since PHP doesn't have a well-thought out exception system/std. lib as Python does, you can't catch anything in that situation in PHP).
- cheald 15y agoIn Python, if you're expecting a potentially missing key, you can just use dict.get('key') rather than dict['key']. The equivalent in PHP would be something like: $val = array_key_exists('key', $dict) ? $dict['key'] : NULL; Being able to say "I expect a potentially nil value (and am okay with that)" via get() rather than array index is both semantically useful, and far more beautiful than the PHP equivalent.
- schiptsov 15y ago"Perfection is achieved not when there is nothing more to add, but when there is nothing more to cut off." Adding fancy syntax does not magically transform that crapware to something almost perfect like python3 or ruby (in its way) where these syntactic forms are among foundations of the language and are supported through all basic idioms. ^_^
- Luyt 15y ago$I $wish $they $would $get $rid $of $prefixing $every $variable $with $a $dollar $sign.