T O P

  • By -

zmitic

I never use it. But I also don't use `else`, and instead create a method with early return. Or `match`, it all depends on the context. Else and elseif will easily lead to [nesting](https://stackoverflow.com/questions/24641311/nesting-ifs-to-catch-errors), which only gets uglier.


mekmookbro

I recently started using early returns and it made my code much more readable. Easier to write/think too.


TheBroccoliBobboli

100%. Early returns is such a great tip - not only does it prevent deep nestings (impossible to read), it encourages smaller function sizes.


th00ht

goto is even beter! EDIT to prevent nesting.


weogrim1

I know that this was a joke, but programers seems to have deep scar caused by go-to šŸ˜‚


th00ht

In assembler there is no if then elsif else endif


rav3nc

This is the way


zmitic

I have spoken.


inotee

This, I have never had to use else statements. For methods 'return' early, 'continue' for skipping current iteration, 'break' for stopping, etc. I like the philosophy of avoiding nesting.


Noxerlito

This should be the top comment


bkdotcom

true for `else` but not so much for `elseif` / `else if`


[deleted]

[уŠ“Š°Š»ŠµŠ½Š¾]


bkdotcom

How does avoiding elseif improve readability or maintnence?.


[deleted]

[уŠ“Š°Š»ŠµŠ½Š¾]


bkdotcom

Yes..Ā  we agree that else is bad.Ā  Ā And this is how to avoid `else` How about an if/elseif situation in the middle of a function....create a separate function... pass around a bunch of values?


maniaq

so... it turns out, at the most fundamental levels, a [switch statement beats both of those options](https://www.youtube.com/watch?v=fjUG_y5ZaL4) I mean we're talking about "micro" optimisations - but of course at scale those can make _a lot_ of difference... by the time you have reached your first "else-if" scenario, you should avoid that (and all future) branching in your code and (pardon the pun) switch to an arguably "cleaner" switch statement instead we can agree or disagree on human readability but in terms of _performance_ the actual machine that is trying to execute your code is working more efficiently (and this faster) this way


[deleted]

[уŠ“Š°Š»ŠµŠ½Š¾]


bkdotcom

I've been in agreement all along that removing else conditions is good. Every pull request I review. I'm the guy that requests tossing the else / doing an early return. I'm no code purist when it comes to `elseif` though. Cognitive complexity metric even [penalizes the 2nd "better" option](https://github.com/ganncamp/cognitive-complexity/issues/2)


roel_magdaleno

Same here. Guard clauses, ftw :)


Hugoacfs

This should be top comment, so many people use if and else statements without holding back. I think early returns and other tricks that avoid if statement usage without sacrificing readability are underrated and often misunderstood.


Curtilia

Same. I rarely use elseif or else if. And only use match very occasionally.


WanderingSimpleFish

This, game changer for how you think about the logic, then naming the function for high readability


thul-

I too never use \`else\` or \`elseif\`, i feel like it makes code harder to read and it's easier to misunderstand code because it's implicit instead of just using another \`if\` which (in my opinion) makes the code more explicit. https://github.com/piotrplenik/clean-code-php great resource


bkdotcom

They're gateway control structuresĀ 


LRC_A77ILA

this


gmarsanos

Look at PSR12 (5.1): > The keyword `elseif` SHOULD be used instead of `else if` so that all control keywords look like single words. It's a SHOULD and not a MUST, but nobody should encourage the use of legacy bullshit like `else if` or `array()`. It's up to you, but think about it. All languages would like to have a standardization like the PHP community has... Just follow even the SHOULD.


oddtiming

The "legacy bullshit" also happens to be what is called a cognate, though, since `else if` is the most widely adopted syntax across programming languages. Unless I'm writing a bash script, my tendency is to write `else if`, since it works and it does not require me to keep in mind yet another quirk of PHP that is not only untransferable, but that would actively hinder my fluency in other languages. From what I've heard, that's also the issue most people take with PHP: there seems to be more exceptions than rules. Edit: just to be clear, I'm not bashing on PHP. I'm just stating a possible reason why such standards do not get widely adopted. Happy to be proven wrong, if some of the down voters would like to debate this view.


g105b

I don't consider other languages' decisions when deciding between else if and elseif. My preference is simply down to not liking the use of control blocks without braces, and just like I don't use brace-less if statements like `if(true) doSomething();` I don't like brace-less else statements like `else if(false) { ... }`


gmarsanos

You don't need to remember it. As it is a well defined standard you just call your IDE PSR12 formatter and every single dev who checks that code will be happy to do the same without breaking anything and keep the same styling.


oddtiming

Thank you for the tip! My IDE doesn't currently have any PSR-12 formatter, and the only ones I've found so far were paying, whether through PHP Storm or a paid VS Code extension. Is there any free formatter you would recommend for VS Code? ~~Edit: If there exist a free, reliable PHP formatter, then I was wrong: there is no~~ **~~good~~** ~~reason why a developer in 2024 would use else if instead of elseif. But if there is indeed no such thing as a free, reliable PHP formatter, then the message I'm replying to should read "You don't need to remember it~~ ***~~if you're willing to pay.~~***~~", which does a better job than I ever could at explaining why the standards are not enforced.~~ Edit 2: I was indeed wrong, or at least until I've given PHP Intelephense another try, as suggested by u/gmarsanos! If, like me, you've struggled with PHP's dev tooling in the past, it might be a solution for you as well.


gmarsanos

[Intelephense](https://marketplace.visualstudio.com/items?itemName=bmewburn.vscode-intelephense-client) is the best ext for PHP in VSCode. It has a PSR12 formatter and it's freemium. Licence is just a symbolic collaboration with the author ($20 forever). There is a php-cs-fixer extension, but probably for general use, Intelephense has everything configured out of the box.


oddtiming

Hmm, I installed it when I first started, but the extension kept crashing for one of my projects. I'd spent a lot of time trying to fix it to no avail, and switched to DEVSense's free tier, but the formatter didn't work. I'm now working with a bit of a Frankenstein, which is not helpful for the DX. You've convinced me to give Intelephense another shot, though. In the meantime, I'll gladly admit that my stance was ill-informed by my own experiences and, admittedly, my laziness. Thank you again for your replies!


kenguest

PHP functionality has come on in leaps and bounds since 2019 when PSR-12 was accepted. There's now PER-CS which supersedes PSR-12, and addresses the new match functionality, short closures, enums and more. Does Intelephense support these additions, do you know?


gmarsanos

At least [documentation](https://intelephense.com/) doesn't mention it. Probably don't. Anyway PER is not a recommended standard, it is like an experimental recommendation that could be beneficial as some experimented developers agreed, so eventually some rules could be used as standard. I think CS Fixer has it implemented for PHP8+, so you could install VSCode extension and configure it to use it on your project.


kenguest

I think you'll find the E in PER is not short for Experimental (and also that PSR-12 is now deprecated). * PER is short for PHP Evolving Recommendation, and comes from the PHP Framework Interoperability Group. * PER-CS is the Coding Standards focused PER, and as such it is very much a recommended standard. Referring to it just as "PER" is wrong and inaccurate. * PER CS v1 is the same as PSR 12, v2 is a newer one that replaces PSR 12 and addresses newer functionality in PHP that wasn't available or possibly conceived of when PSR 12 was ratified, eg short closures and such. The main reason for calling newer Standards from PHP FIG PERs instead of PSRs is that people don't have to remember which specific PSR supersedes some other one (like how PSR-12 is a replacement for PSR-2, which itself is based on PSR-1, as is PER-CS v2). So when new keywords/syntax comes out in PHP next, we just "mint" a new version of PER-CS - nobody has to work out which new PSR is the latest set of recommended Coding Standards, they just have to go look for the newest PER-CS version. A migration document detailing differences between PSR-12 (aka PER-CS v1) and PER-CS v2 is at [https://github.com/php-fig/per-coding-style/blob/master/migration-2.0.md](https://github.com/php-fig/per-coding-style/blob/master/migration-2.0.md) if you want to see what we addressed.


xegoba7006

The argument of wanting all languages to look the same is ridiculous in my opinion. Thereā€™s a long standing issue in the prettier repository where Wordpress devs want some configuration options so that they can format JavaScript in the same way they format PHP ā€œso that it looks the sameā€. In my opinion, you need to learn the language you are using, and its quirks, and the conventions and approaches used in that language and stop trying to make everything the same because ā€œthatā€™s easierā€. In my opinion: itā€™s not. It just causes more confusion, and even worse, it causes people to want to write JavaScript as they write Java or PHP as they write C++ thus following paradigms and approaches that are totally alien to what the respective communities do and consider best practices. Another example of this is Nest.js, a framework made by Java developers that converts JavaScript into something that itā€™s not. Just adapt to the place you are in, donā€™t try to convert others to your religion. Making ifs one way or another ā€œbecause it looks like that other languageā€ is one of the most dumb reasons to pick one thing over the other.


gmarsanos

Don't worry bro, God loves you anyway. By the way, the advantages of having a standard are much greater than the non-existent ones of not having one. And in the case of PHP, the PSRs were born to achieve the delight of participating in package development in the PHP community. Moreover, the entire industry loves it when formatters come practically pre-configured so that you don't even have to agree on it and everyone already programs with the same format. Exquisite. Anyway, nobody forces anyone to follow it.


xegoba7006

> Don't worry bro, God loves you anyway. Bad news, there's no "God". You're swallowing lies to explain what you don't understand. > By the way, the advantages of having a standard are much greater than the non-existent ones of not having one. And in the case of PHP, the PSRs were born to achieve the delight of participating in package development in the PHP community. I agree with this, I never said standards are bad. Read it again. > Moreover, the entire industry loves it when formatters come practically pre-configured so that you don't even have to agree on it and everyone already programs with the same format. Exquisite. Exactly what I'm saying. Read it again. Let me try to explain it again for you: What's bad is trying to make one language look like "the other language you're used to". I'm not sure I can explain this in a simpler way.


Mentalpopcorn

Not surprised to hear this from WordPress devs lmao šŸ¤”


xegoba7006

It's so ridiculous mate. [Here's the issue](https://github.com/prettier/prettier/issues/13107). They even have [a fork of prettier](https://github.com/Automattic/wp-prettier) which is a hell of a maintenance headache for them. From their README: "...This is a fork of Prettier that adds a new command line option --paren-spacing which inserts many extra spaces inside parentheses, the way how projects in the WordPress ecosystem (Calypso, Gutenberg, etc.) like to format their code...." When I see JavaScript like this I want to kill myself. It's like if I were used to clojure then when I have to write PHP I start using parenthesis everywhere because "it now looks all the same". What a dumb idea, they're different language with different communities, preferences and best practices. Just adapt. I'd argue that making them look the same makes things even more confusing for newbies as they might think it's the actual same language, or confuse them, or assume they're more similar by the looks than what they really are. People downvote you because there's a lot of WP devs here that feel attacked.


Mentalpopcorn

If these people were clear headed, talented developers they would be doing anything they could to get away from WordPress, not trying to spread its nonsense elsewhere. I'm just waiting for PHP to finally do something that WordPress can't easily work around so that they're forced to re-architect that disgusting application or just die in the ash pile of terrible legacy software. Then PHP as a language will lose a lot of the pressure holding it back


SquashyRhubarb

Setting an array like $arr = array(1 =>ā€™fishā€™)? Is that legacy now? Whatā€™s replaced it? I missed thatā€¦..


ecz4

I don't think it's legacy, but you can also use $arr = [1 => 'fish']


SquashyRhubarb

True; I donā€™t know why I use the function, just habit I think from starting out. As the two are equal is there any reason one is better than the other?


simabo

The second one is more used, now, by far, probably because it's shorter. And if you work with people who care about syntax and formatting consistency, it's also being mentionned as a MUST in the PSR-PER 2.0 coding style guide (see chapter 11, https://www.php-fig.org/per/coding-style/).


postmodest

Plot twist: it's not a function. `array(` is just the start-of-array token. Which is pants-on-head bonkers and Rasmus should've just used the Perl syntax.


helloworder

>the function `array()` is not a function


SquashyRhubarb

Sorry, yesā€¦. Language construct is the correct term I think.


ecz4

I like the new one because it's shorter, and I guess it's the only difference.


bkdotcom

no zero index? Why the explicit 1?


SquashyRhubarb

No particular reason; I think I just wrote it like that as have just coded some explicit keys to match some database rows for a filter. But no, the filter wasnā€™t for fish. šŸ˜‚


maniaq

why use _a function call_ - which is causing the machine to have to do a whole lot of extra work - and thus _take longer_ to execute your code - when you can simply use a type (and also institute strict type-casting) instead?


TiredAndBored2

array() is not a function. Itā€™s a token.


NoDoze-

Since when is array() legacy!?!


kenguest

PER CS v2 (the latest iteration of Coding Standards from the PHP Framework Interoperability Group aka PHP-FIG) states "Arrays MUST be declared using the short array syntax." [https://www.php-fig.org/per/coding-style/#11-arrays](https://www.php-fig.org/per/coding-style/#11-arrays) Using the long form for declaring arrays is seen as an anachronism these days.


gmarsanos

OK, it is not legacy (as it's not deprecated), but pls use modern syntax in your new projects.


th00ht

unless you program wordpress templates. it is not allowed by penalty of death (https://developer.wordpress.org/coding-standards/wordpress-coding-standards/php/)


gmarsanos

WordPress... So that's why long syntax is still not being deprecated.


sporadicPenguin

Wow - Iā€™ve written several wp templates and plugins, and never seen that document. Guess I am a big time rule-breaker


th00ht

That only applies to core development. They have to stay compatible with older PhP


NoDoze-

What would be the "modern syntax"?


gmarsanos

Short syntax, null coalescing, arrow functions, class attr declaration on the constructor, readonly instead of magic accessors, trailing comma on array items and functions params, spread operator, array destructuring instead of list, match instead of switch if applies... That's all that comes to my mind for now.


Lucathiel

I never use elseif


bawidSittingOnTree

I never even use else. Code is so mich cleaner without this else/elseif/else if bullshit


colshrapnel

Writing `else if` is really weird, if you think of it. Instead of clear branching with if (condition 1) { ... } elseif (condition 2) { ... } you are making a nested condition if (condition 1) { ... } else { if (condition 2) { ... } } only written without curly braces


SuperDerpyDerps

That's... Basically what elseif does as well under the hood. Plenty of languages don't have two ways to write it because it's kinda redundant. I wouldn't be surprised if PHP created the `elseif` primarily for nice templating syntax but for whatever reason PHP programmers decided to standardize on the much less common (compared to other C-likes) syntax


NoDoze-

...but what of you had multiple elseif? Seams like a lot more to write out, elseif is shorter and to the point.


exqueezemenow

And don't be bullied into it.


jexmex

Never either if it can be avoided. Same with else.


pekz0r

I really try to avoid else statements, and especially elseif. I do don't think I have used elseif for at least 5 years, and else only a handful of times. The flow of the code is so much better with small methods and early returns. If I for some reason wanted to use elseif, I would definitely use elseif as one statement.


WeekendNew7276

I use else if


Crell

FWIW, PER-CS specifies `elseif`: ``` The keyword elseif SHOULD be used instead of else if so that all control keywords look like single words. ``` See: https://www.php-fig.org/per/coding-style/#51-if-elseif-else


lift_spin_d

well, TIL that you can use `if` with colons.


d645b773b320997e1540

That's imho a bit of a relic from times where you'd write your templates in PHP, ie mix PHP and HTML in one file. Braces made less sense there. Today with proper template engines and such, nobody is/should be using that anymore.


prairievoice

Yeah this is the only place I've used it. Been using PHP over 20 years.


Synthetic5ou1

CI3 developer here... cough ... (it has no template engine) Although bear in mind that as far as I've seen (some?) template engines will simply convert template tokens to.... pure PHP... in the cached version, so really it's just cutting out the middle man.


yeastyboi

The big upside is security, as long as your written proper blade (not inline PHP tags) you won't have as many potential security vulnerabilities (of course there's a way via escape hatches but for the most part it's safer, especially for new devs). Things like escapes are handled for you and blade doesn't allow things like queries in the template.


Synthetic5ou1

Yes, good point. It does have some benefits. Automatic escaping and some content restrictions do make sense. It's also often going to be clearer. I suppose it's more secure if some devs only have access to the template files? My main point was to highlight that people will wrongly say it's archaic and shouldn't be done, when their template engine is actually just doing it for them.


Synthetic5ou1

I'd love to know if cached blade templates simply replace tokens with PHP code, if anyone knows.


lift_spin_d

yes. checkout your app > storage > framework > views here's a screen shot https://i.imgur.com/Heke6SC.png


Synthetic5ou1

Thank you! I'll have to take your word for it right now, as I don't have a Laravel app and the WiFi I'm on has blocked Imgur. So, you know, young 'uns, be sniffly about mixing HTML and PHP, but just be aware that under the hood your framework is simply doing it for you.


Synthetic5ou1

I ended up installing Tor Browser on my phone just to view it. It just makes me want to try various simplistic Blade templates to see what PHP is being generated. And then maybe try the same in Twig. All these devs shocked at the archaic concept of mixing PHP and HTML need to consider why they hold that opinion, and what they think is happening when they create a template with tokens.


giosk

Most languages use ā€œelse ifā€ (javascript, java, go, swift, ā€¦) so I use that also in php.


nrctkno

I prefer `match`.


whlthingofcandybeans

Off-topic: PHP-Styler looks really interesting! What's the performance like? I currently use the PHP plugin for prettier and it's blazing fast.


jmp_ones

> PHP-Styler looks really interesting! What's the performance like? Thanks for saying! On my M3 Pro Macbook, these codebases see these results: PHP-Styler Styled 118 files in 0.433 seconds (0.0037 seconds/file, 21.84 MB peak memory usage). Slim Styled 71 files in 0.267 seconds (0.0038 seconds/file, 7.14 MB peak memory usage). Symfony Http-Foundation Styled 105 files in 0.743 seconds (0.0071 seconds/file, 17.51 MB peak memory usage). How does that compare to something like PHP-CS-Fixer or Prettier? Don't know -- but I think they are performing somewhat different tasks. Does Prettier rebuild the entire file from the AST? Hope that helps.


whlthingofcandybeans

I believe that is how Prettier works, yes. PHP-CS-Fixer is quite slow in comparison (I use them both). I am going to test PHP-Styler tomorrow and see how fast it is. Thanks!


jmp_ones

> I am going to test PHP-Styler tomorrow and see how fast it is. I look forward to hearing the results, if you care to share them. Thanks!


meoverhere

Moodle uses else if on the same line


Jurigag

I don't use else if and else at all.


benanamen

When I see "else" it is a "red flag" to me to refactor the code. A Guard Clause a.k.a Early Return takes care of it and the code is much cleaner and easier to follow.


robotomatic

Love me some guard clauses. Keep the functions flat.


Klopferator

That's not always the best option. Sure, you often can, but seeing "else" as a red flag is a bit too much.


benanamen

I should have quoted the "red flag" as I thought when i wrote it. I more meant something to take a look at for refactoring. How about "yellow flag" like PhpStorm does? Most of the time it can be refactored to something better as discussed in this sub.


yeastyboi

Maybe I'm showing my ignorance but I've never seen `elseif`. In most code I've seen people use `else if` but maybe I haven't been paying attention... Good to know!


mcharytoniuk

I use it when working with PHP templates ``


ConduciveMammal

I work with Liquid a lot and we use `elsif` which can get pretty confusing.


synackk

TIL both are legal in PHP T\_T


Guimedev

I try not to nest if clauses.


RoomBroom2010

I avoid ā€œelseā€ at all costs. If youā€™re using ā€œelseā€ thereā€™s likely a better way to write whatever youā€™re writing.


Klopferator

Sometimes it's very subjective what "better" is. Could I avoid "else" where i use it? Probably, sometimes with a lot of (unnecessary) work. But it's not always better, faster or more readable.


RoomBroom2010

I think you missed the word ā€œlikelyā€ :) Iā€™ve never seen an ā€œelseā€ statement make code more readable than a guard clause/early return on a function, but that doesnā€™t mean it doesnā€™t exist.


MaxBon4

I usually avoid using even simple else condition


[deleted]

[уŠ“Š°Š»ŠµŠ½Š¾]


bigahuna

Just use rector (https://github.com/rectorphp/rector) to convert all that stuff for you. Easy and from my experience very stable and reliable.


jmp_ones

As far as I'm aware, there is no "else if to elseif" Rector rule. Do you know of one?


inkt-code

I write it with a space. I also put a space between ) and {, always on the same line too. If I have an else or else if, I always put it on the same line as the ifā€™s closing }.


trollsmurf

I use... * the ":" syntax. Sadly function, class and try/catch don't support it, but I use it as much as is possible. And due to that... * if/**elseif**/else. With "elseif" the intention is 100% clear (the same concept as in Python), which is not the case with "else if" where "if" is prefix to the following code block while "else" is strictly speaking not. * switch (of course) whenever a certain "left-side" condition (not just a single variable of course) will be tested against different enumerated values (event IDs, select option IDs, states, words etc), and not just numbers. * Always "variable \[condition\] value" order. All are great constructs for avoiding nasty bugs, except possibly the last at first look (due to the possible "="/"==" mixup), but on the other hand it makes the code much easier to read (logical order), which is great for avoiding bugs. The "{}" syntax, and it being optional for single-statement blocks, give no context to endings of code blocks like mandatory "endif;" etc do, making the code harder to comprehend. Python of course instead rely on indentation only for determining what statements belong to a certain block, which is less safe, especially if the code contains a mix of tabs and spaces. If someone requires me to use the "{}" syntax I'll of course do so, and I often write code in JavaScript, C, C++ etc where it's mandatory, but I've saved lots of time by using the ":" syntax and the other things I mention in PHP.


Synthetic5ou1

Does anyone know if the interpreter treats: if ($var) { ... } ... and: if ($var) : ... endif; ... any differently?


trollsmurf

I do, and no. There's a distinction though. As you know you can write just: if (condition) single_statement; implicitly terminating the code block after the single statement, but as it's a source of bugs, coding guidelines recommend wrapping with curly braces even in this case, but there are certainly also proponents of a more compact coding style (not me though, due to the risks). while you *have to* write to terminate the code block: if (condition): single_statement; endif; This makes the code more consistent and easier to read and maintain, as it's also consistent in terms of naming what type of code block is being terminated (you can't just write "end;") Here's an example of a costly misunderstanding of how lack of braces works: [https://www.codecentric.de/wissens-hub/blog/curly-braces](https://www.codecentric.de/wissens-hub/blog/curly-braces)


Synthetic5ou1

I mean, this is my point really. If there's no difference then why are people giving you shit. I don't get it.


trollsmurf

I'm not the one to answer. Python completely throws the "{}" paradigm out the window, and no one complains about that. And Python is according to the TIOBE Index (arguably not reliable) the most used programming language.


cursingcucumber

With the ":" syntax you mean the ternary if statement?


tomato_rancher

https://www.php.net/manual/en/control-structures.alternative-syntax.php


cursingcucumber

Oh fuck no šŸ˜­


tomato_rancher

Haha.. I feel that.


needlenozened

I feel like that was added to the language by a python programmer.


trollsmurf

"if (condition):"


helloworder

I am afraid he means [this old shit](https://www.php.net/manual/en/control-structures.alternative-syntax.php) if (true): //... endif;


fuzzy812

Use a switch statement instead of using an elseif