PHP's Oddities (flowtwo.io)

• mfonda 4 hours ago

After over two decades of working in PHP, I'm now working in Java. PHP is basically Java-lite. I am absolutely loving the compile-time safety of Java, but I dearly miss PHP's maps and arrays. In Java, the amount of verbosity for defining a map/list and operating on it is overwhelming.

Modern PHP is great. Many powerful language features, excellent performance, great community and package ecosystem, and decent enough safety with modern static analysis tools.

I'm not too sure I agree with the author's complaints here. When using something like array_filter, you're typically mapping from collection to collection (i.e. you don't care about the first element--you care about the whole thing) and so this problem is really a non-issue. The next follow up step would usually be foreach, or another operation like array_map, in which case it's a non-issue.

If you really do need the first element, you can use array_first. And if you really do need a fixed-sized collection, you can use SplFixedArray.

The point on properties is valid to an extent, but IMO not really an issue you commonly run into in the real world (regardless of language, your constructors should generally return an object in a usable state).

• mdavid626 3 hours ago

If I have an “array” and can do array[0] to get first item, but when I filter this array and array[0] throws an error, that’s super weird. What is the meaning of [] or what is an array even? The language forces me to understand how it is implemented under the hood. That’s exactly what the author says: leaky abstraction.

• mfonda 3 hours ago

An “array” in PHP is an ordered map.

• pavel_lishin 2 hours ago

Isn't exactly their complaint? It's called an array, referred to consistently everywhere as an array, but it just ... isn't.

• lofaszvanitt 41 minutes ago

All PHP needs is python's flexible and convenient manipulation of lists/dicts/objects. Plus dropping the end semi colon and it would riiiiiiiiiiiiiiiip the fabric of spacetime.

• calvinmorrison 23 minutes ago

yes I say this now very often, that PHP has morphed into runtime Java. Quite nice in some ways.

In PHP though the STDlib is not very well thought out, it may be fun(needle,haystack) or fun(haystack,needle) and you just have to remember

empty() will do weird stuff like a string with the value "0" is also empty, so not great for parsing things.

A lot of footguns and the best way to avoid that is with a decent linter that lets you be picky

another thing I mention is avoiding the array_ stuff because of aformentioned reasons, it's easier to remember/reason about boring loops unfortunately.

• Onavo an hour ago

Have you tried Lua or one of its variants?

• shevy-java 4 hours ago

> Modern PHP is great. Many powerful language features, excellent performance, great community and package ecosystem

I heard this a long time ago about perl. CPAN is great.

Well ... perl entered the fossilized era. I think people do not really observe things correctly. I am noticing the same with ruby right now - everyone sees that ruby is in decline, very strongly so, in the last 3 years. Yet you have blog posts such as "ruby is not dying - it is aging like fine wine". And these are all NOT BASED ON FACTUAL ANALYSIS. I still think ruby is a great language, but if people are not realistic in their assessment of a situation, what does this tell us about people's evaluation in general? People seem to shy away from criticism. You can see this on reddit too, where moderators ban and censor willy-nilly, or even on github, where you can also quickly get eliminated for not conforming to xyz. It's as if some people are very afraid of strong opinions. I don't understand why - an opinion that is objectively false, can be shown to be false.

• chamomeal 3 hours ago

People absolutely have VERY strong opinions and voice them constantly. True of every language but especially php. Almost feel like it’s more acceptable to rant about php than to praise it

• susam 2 hours ago

I attended a talk by Rasmus Lerdorf at a FOSS conference in 2006. It has been a long time, so I remember only a few things from the talk, but one thing I remember him talking about is how people love to complain about PHP, often on forums that are themselves written in PHP.

• internet2000 2 hours ago
• unethical_ban 42 minutes ago

I know I used to have the impression of PHP as a messy language because I last worked with PHP4. It's come a long way since then, though I don't use it.

• xp84 3 hours ago

> objectively

> Ruby is dying

How exactly do you define these “objective” criteria for such sensationalism?

• greybeard69 4 hours ago

Mate, not to be rude but your entire comment isn't based on factual analysis; it's a rant about unrelated languages.

• customguy 3 hours ago

> People seem to shy away from criticism.

What actual criticism of PHP is anyone shying away from?

PHP got bashed for such a long time, while simply nothing steps up to do what it does better. Something that, for example, is available on every webhost you can just throw files at, where all (meaningful) config and state can be in those files.

• xp84 3 hours ago

I used to really love the dead-simple ease PHP brought to server-side dynamic web stuff too. But when shared cpanel type hosting was orders of magnitude cheaper than anything else, that was a way bigger deal. Today you can deploy a node.js app (all the same “just a script” advantages of PHP) to a half dozen places for free, and for the next step up, a smallish instance at Hetzner, DigitalOcean or whatever, where you can just run any arbitrary container, costs less than those shared hosting once did.

Why do I bring up containers? Because part of why PHP was so dope in this way was the way you can just define 1 file per endpoint and drop it in public_html, and have no server setup to do. Running say, Rails or ASP.NET or a Java site back then meant doing… a lot more, to your server.

But with Docker, you can just steal a good Dockerfile template from someone else, and it’s just like 3-4 simple files for you to manage for a simple Sinatra (Ruby) or node.js version of the “one-off PHP file” things.

• customguy 2 hours ago

But I don't want to manage 3-4 files, I want to manage zero files. I don't want half a dozen hosts, I want hundreds of thousands. It's not about costs, I really mean the simplicity and pervasiveness. PHP apps that are simple (in that they don't require any "rare" modules to be enabled) can easily be written to not run in relative folder structures, you can move them around like .exe files if you will. Not "like moving an exe file and then just updating a few lines in this file over there", that is a completely different thing for me.

edit: Granted, I agree that if you want to do all sorts of things on the internet, maybe PHP is not the right choice. But for simple, dynamic web things that I want to just make and then run like this forever, that I can work on but don't have to? PHP and vanilla HTML and Javascript are where it's at for me, hands down. Everything else I know is either too new or seems to have constant churn or issues. That you hear nothing about PHP other than complaining it's "outdated" or whatever from the outside -- always "why are you using this?" never "why oh why am I using this?" -- is because it just hums along, IMO. I like it better than Python, and I kinda view it as in that class.

• Pay08 an hour ago

I've always thought that the core idea of PHP, the intermixing of code and HTML is an incredibly elegant solution to a very difficult problem. But at the same time, the language itself does suck (although I won't discount the improvements it has made). I would really love for there to be an entirely reimagined PHP from the ground up, and to hell with backwards compatibility or availability.

• krapp an hour ago

There was. It was called Hack[0]. Among other things it had XHP built in so you could write HTML natively (as opposed to concatenating strings) and define your own templates easily[0]. It even handled escaping. It really improved on a ton of PHP's flaws.

Unfortunately newer versions of PHP killed it and it's dead now, and even more unfortunately while PHP absorbed a lot of features from Hack, native XML was not one of them. There was even going to be a Hack version of the Composer package manager but that never got finished AFAIK. Distros stopped supporting it. I think I still have my half-finished attempt at a Hacker News fork in Hack sitting around on a hard drive somewhere. I can't even find an environment to run it in anymore.

[0]https://docs.hhvm.com/hack-overview/

[1]https://docs.hhvm.com/hack/XHP/introduction/

• skydhash 3 hours ago

You can say the same thing about lisp (and C in some regards). Sometimes a language is done and anything you add to it is breaking things for no sizable improvement. And if your primary target is Unix, it’s often so easy to write a shim for C/C++ libraries that you don’t bother implementing your own version of stuff.

• Pay08 an hour ago

Which lisp? :P

• chuckadams 4 hours ago

> This lax behaviour for property definitions makes writing code around them harder. Especially when you take into account that any object can have properties dynamically added to them:

Doing so now raises a deprecation warning, unless you add #[AllowDynamicProperties], and PHP 9 will convert it to an error. I'm told this will simplify internals and unlock optimizations.

Arrays are still fairly awful, but generics may become a reality sooner rather than later, and on that could be built Vec and Dict types, à la Hack. PHP is going to be stuck with arrays as they are now for forever, but they'll at least become optional for new code.

• Ayesh 4 hours ago

PHP has quite a lot of oddities such as how loose comparisons (`==`) are made, numeric-strings, and type coercion. But the two oddities mentioned in the article are not that "odd" with a bit of context.

- PHP has `SplFixedArray`[^1] that work similar to the standard arrays you expect from other languages. SPL extension is always available in PHP 5.3+, it is not even possible to compile PHP without it anymore. There is no specific type for list-arrays and associative arrays, but there is an `array_is_list` function to quickly check it.

- For typed properties, if a property is not typed, it is effectively considered `mixed $var = null`. If the property is typed, and has no default value, then it is considered uninitialized, and not allowed to access.

[^1]: https://www.php.net/manual/en/class.splfixedarray.php

• larsnystrom 2 hours ago

I've been writing PHP for 20 years now. It's my bread and butter.

The one thing I really wish PHP would add is structurally typed objects. I really miss it when moving back and forth between PHP and TypeScript.

They could call them anonymous objects if they want to (that would be a more culturally correct analogue to anonymous classes).

Like, I wish it was possible to do

  {
    string $mystring = $myvar,
  }
and have it be equivalent to

  new class($myvar) {
    public function __construct(
      readonly public string $mystring,
    ) {}
  }
and then be able to typehint it like

  function ({ string $mystring } $myobj) {
    echo $myobj->mystring;
  }
and honestly, why not go all the way and allow type definitions/aliases, something like

  type myobj_type = { string $mystring };
That'd be great.
• idoubtit an hour ago

You can do that. Of course, PHP's native types are quite limited, but a phpdoc syntax should work with static analysis tools. For instance:

    /** @psalm-type MyobjType = object{mystring: string} */

    /**
     * @param MyobjType $myobj
     */
    function (object $myobj): void

Here are some documentation and examples:

- For Psalm, see https://psalm.dev/docs/annotating_code/type_syntax/utility_t...

- For PHPstan, see https://phpstan.org/writing-php-code/phpdoc-types

It may work in your IDE (autocompletion, etc.) but there is no standard on this side. Some IDE have their own parsers, others use one of the LSPs for PHP.

• larsnystrom an hour ago

Yeah, at the moment we use arrays as anonymous objects and phpdoc+phpstan to verify the types, but I want it in the language. PHP already supports intersection and union types, it really feels like just skipping the naming part and going all in on structural typing is not that far fetched by now.

• chrisandchris an hour ago

About undefined vs. NULL:

> Not a warning—a FATAL error occurs if you try to access an uninitialized property. This comes up a lot in cases where you try to deserialize data into a PHP object. If a field's data isn't present you might not initialize the property at all.

I don't think that is an issue, except in interpretet type-unsafe languages it is harder to anticipate when writing code whether that value is NULL or undefined/uninitialized. E.g. it is basically the same in C#, but here the compiler warns you that the value is not initialized and forbids some actions (like reading the value of it).

• t1234s 3 hours ago

The last part about "$" is epic.

• kyriakos 3 hours ago

petition to use Euro symbol when coding PHP in EU.

• over190bpm 2 hours ago

It reminds me of this great blog post: https://aloneonahill.com/blog/if-php-were-british/

• bwoebi 3 hours ago

Arrays in PHP are mostly confusing if you are used to them in other languages. Instead of $array[0] - the first element is accessed via array_first().

Having them as key-value means, that you can easily just remove some items in the middle, during iteration etc. No automatic shifting happening.

The thing which bites me is when some internal functions actually reindex the array. array_filter does not, but for example array_reverse, array_slice etc. do (preserve_keys always defaults to false). And for array_merge too, but there it's no array_merge(preserve_keys: false), but instead the + operator. (Why is this operator overloaded?!)

On the topic of the uninitialized state, as co-author of that RFC:

I agree with the author that nullable properties should have been auto-initialized to NULL. I haven't ever seen any benefit of an uninitialized state for these. Some co-authors of that RFC disagreed and wished for consistency with the other typed properties. The good thing probably is, that we still could opt to change this with a relatively minor BC break.

For non-nullable properties, I do think there is value. Not every value is actually available/ready in a constructor. Sure you can assign dummy values to properties. But it's requiring you to then manually guard/assert that the property is actually initialized. If you happen to access a non-nullable typed property without isset(), then your code is likely broken anyway and I'm grateful for the Error exception thrown.

Also, PHP has this peculiar feature of ReflectionClass::newInstanceWithoutConstructor(). This is forcibly having an object in an uninitialized state. Whether that feature should exist or not is a good question, but in practice it's helpful for object hydration for example. This was one further motivation to introduce the uninitialized state.

The author of the post suggests checking at the constructor boundary. But this doesn't inhibit objects leaking / not finishing the initialization properly. (class Foo { public stdClass $object; function __construct() { global $foo; $foo = $this; } } new Foo; $foo->object ... is now still existing? PHP doesn't have mechanisms to invalidate objects at a distance. That would be the alternative, but also spooky.) Some choices need to be made, and all choices will have some rough edges.

Side note: I personally never use is_null(), but nearly always isset(). This nicely checks for the uninitialized state too. Static analysis tells me anyway, when I access a variable or property name which can never exist.

• idoubtit an hour ago

There's one problem with arrays that I haven't seen mentioned here or by the OP: when inserting a key-value, the type of the key may change. For instance ["4" => "four"] === [4 => "Four"]

This can lead to some unexpected behaviors. For example, I've already been bitten by `array_merge()` whose result is different if its parameters are arrays with numeric indexes.

    array_merge(["4 " => "four"], ["5 " => "five"])
    // ["4 " => "four", "5 " => "five"]

    array_merge(["4" => "four"], ["5" => "five"])
    // [0 => "four", 1 => "five"]
• makeitdouble 4 hours ago

To note, it is surprisingly refreshing to completely forgo instanciable classes on a modern codebase.

Phpstan deals well with type definitions, arrays are powerful enough to contain whatever needed, and functions can be stored and passed around easily enough.

• chuckadams 3 hours ago

Array shapes are still second-class citizens defined in phpdoc, with an inferior editor UX, and lack of any run-time enforcement. A proper record type for PHP with value semantics would be an ideal solution for me. Would go nicely with the pattern matching proposal that's still incubating.

• skydhash 3 hours ago

If there is one thing I love about Clojure and Common Lisp, it’s that you’re not supposed to care about the shape of a complex data if it’s external to the module. What really matters are the functions that are exported and their signature. Anything that’s not standard in the library should be used as an opaque blob. And something like CLOS is about making this easier to define.

• leeoniya an hour ago

surprised not to see http://phpsadness.com/ here

• RobotToaster 2 hours ago

How could you leave out left-associative ternary operators?

• love2read 4 hours ago

I’d love to see a post like this for JS that actually talks about things people run into. Usually when people make a post like this in js, its about archaic things nobody actually uses.

• dylan604 3 hours ago

https://www.destroyallsoftware.com/talks/wat

Archaic maybe, but still brings a smile

• nasretdinov 4 hours ago

if("0") {} being equivalent to if(false) {} still gives me nightmares even though I've stopped using PHP for at least 6 years now :)

• moritzwarhier 4 hours ago

I knew this in and out, but as a Full-Stack PHP/Symfony/Frontend/JS guy who pivoted to mainly TS for b2b stuff, I still have to occasionally enter

  !""

into the browser console just to be sure, during code reviews :D
• tredre3 3 hours ago

In JS/TS:

    "0" == false : true
    ""  == false : true
    " " == false : true
    "1" == false : false

    !"0" : false
    !"" : true
    !" " : false
    !"1" : false

In PHP:

    "0" == false : true
    ""  == false : true
    " " == false : true
    "1" == false : false

    !"0" : true
    !"" : true
    !" " : false
    !"1" : false
Honestly the only way to remain sane in either, but especially if you use both, is to always use === and never use boolean logic (!) when a string could be involved.
• moritzwarhier 2 hours ago

That's what I say in code reviews as well. Same for numbers.

!someValue is useful only for:

- booleans, including optional booleans (which is why every bool flag should default to false)

- undefined, null (falsy), or object/function (truthy)

It's nice for the second variant to also cover falsy NaN or things like this, for example for forms.

I guess that's where

  !!""===false
comes from.

But it's this exact case that keeps tripping me up.

What about empty arrays?

Per my original comment, now I'd have to look up if

  ![]
is false in PHP, or just empty([]) === true

.

So yea I agree, and extend your case to PHP "arrays" (in JS,

  !![] === true
is

  true
• kif 4 hours ago

Also `empty("0") === true` is a common gotcha.

• ceejayoz 4 hours ago

Every time I work in another language I miss PHP’s arrays.

• conceptme 4 hours ago

Basically every other language has the same functionality (or better) as a hashmap.

• ceejayoz 4 hours ago

I’m well aware of them. I’m not sure I agree with “better”.

• xp84 3 hours ago

I’m very curious to hear your take on this. I started out on PHP for about 4-5 years then moved on to Ruby and JS. I never once had any fond thoughts for PHP’s split-personality array thing. So I’m very curious what it is that other people appreciate about it.

• ceejayoz 3 hours ago

Having to switch implementations and potentially functionality because, say, the order of the collection matters now is rather annoying, IMO.

• lazka 3 hours ago

That array keys are auto-coerced to integers has bit me multiple times.

• rokkamokka 4 hours ago

They are an incredibly versatile tool for sure. Even more so wrapped in a Laravel Collection

• bakugo 4 hours ago

For me, it's the exact opposite. Every time I work with PHP, I wish I could have TypeScript's properly typed arrays and dictionaries instead of the janky untyped 2-in-1 mess it actually has.

• spiderfarmer 4 hours ago

Absolutely. If you don’t know PHP arrays aren’t actually arrays, the other languages feel inferior.

• cess11 3 hours ago

I like the arrays, they make it feel like a bit of a low level language and there are some weird tricks one can do with them. As for class property behaviour, I kind of get nervous if my properties or the constructor don't enforce default values I can then fit into downstream logic.

One of the best things with PHP is PsySH, or "Tinker" as the laravelists call it. It's not a REPL in the Common Lisp sense, but it is quite nice for an interactive programming shell. I've spent countless hours solving problems very, very quickly in it, and alongside Picolisp pil + and Elixir iex it's one of the earliest tools I install on a new system.

https://psysh.org/

The thing I miss the most is a nice concurrency story. It has become better but it's still a bit of a mess, often it's nicest to just implement workers as PHP and then implement control somewhere else, e.g. Elixir, or grab one of the application servers that are nowadays a thing in PHP.

• conradfr 42 minutes ago

Good old empty() and isset() work on uninitialized properties though.

edit: not sure why the downvote.

• bakugo 4 hours ago

> This example exposes the "uninitialized" state that a property can be in, which is NOT the same as NULL. This distinction frustratingly comes up when you try to do a null check on these properties:

If you're accessing an uninitialized property or checking if a property is uninitialized, you're probably already doing something wrong.

The point of class properties with no default value is that you're supposed to set them either in the constructor, immediately after creating an instance, or via some other method that guarantees they'll have a value by the time you need to read them (such as deserialization with validation).

If you want your properties to have a default "unset" value that you can trivially check for, that's what null is for. The author doesn't make it clear whether they are aware that you can declare a nullable string and give it the default value of null, but I hope they are.

• spiderfarmer 4 hours ago

I think the “bad rep” is coming from developers that stopped developing themselves.

• chuckadams 3 hours ago

I've written PHP off and on since the .php3 extension was a thing, and I can say that PHP very much deserved the bad rap it had for some time. It's evolved beyond most of that, but a lot of that is due to the composer ecosystem making up for it while the behavior of many builtins remains beyond repair. Which is fine, every language has baggage and warts. PHP's warts are sometimes heinously ugly, and they're on full display in many legacy codebases, but modern PHP is something I actually find to be fairly pleasant to develop with, far more than Go or vanilla JavaScript.

• spiderfarmer 21 minutes ago

The most under appreciated thing about PHP is the fact that after 20+ years I can still develop in PHP and never had to learn a JS framework, Rust, Go, Ruby, Java or .NET.

• esskay 3 hours ago

A lot of it came from the rather harmful "php a fractal of bad design" article that used to get posted everywhere despite being highly inaccurate and out of date. Thankfully its fairly rare to see someone daft enough to still try using it in a discussion. PHP's come a very long way since then.

• thayne 2 hours ago

What is inaccurate about it? Maybe it is out of date now, but when I first read it about a decade ago, when I did a fair amount of PHP development, I had personally encountered most of the issues mentioned in there.

I've heard that PHP has improved a lot since then, but I don't see how you could really fix all the inconsistencies, global state, and "oddities" without a lot of breaking changes and really making it into a different language.

• spiderfarmer 24 minutes ago

PHP should learn from JS where you have to abandon frameworks every two years.

• fg137 3 hours ago

No. Bad rep comes from developers who used other languages and never looked back.

• spiderfarmer 26 minutes ago

So they stopped developing in PHP am I right?

• frutjgma 3 hours ago

I did PHP for 15 years. Modern PHP looks good but I still wouldn't go back.

• phplovesong 44 minutes ago

What is even "modern php"? It has the same warts than it had back in the day, last i looked nothing is fixed.

• shevy-java 4 hours ago

All of PHP is an oddity. It is a practical oddity, but also ugly to no ends. I am glad to have abandoned it many years ago.

Surprisingly enough, I was more productive in PHP than I was in perl. Perhaps perl is even stranger than PHP.

• acomjean 3 hours ago

Modern PHP is pretty good. I’ve been using it for a while so it’s comfortable.

I’ve been doing so Perl maintenance lately and I miss PHP. Perl is a lot weirder than PHP. If I didn’t know C or had dabbled in Perl before I would be completely confused. There is More Than One Way to do it (the Perl rallying cry) causes a lot of confusion. The one nice thing about Perl is that it doesn’t really change anymore, and you can see where it positively influenced others.

• phplovesong an hour ago

PHP is fundamentally broken, and unfixable. Its a toy language, and there is no reason to pick it in 2026

• develatio an hour ago

I feel like somebody needs to be reminded of “PHP: a fractal of bad design” :D

https://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/