Hacker News new | comments | show | ask | jobs | submit login
Ask YC: Python vs. PHP
35 points by symbiotic on Apr 8, 2008 | hide | past | web | favorite | 47 comments
So far I have done all of my web programming in PHP. I've also recently learned Python and so far I find the syntax to be annoying (that might be because I'm just used to PHP). But I've heard a lot of buzz on these boards about using Python. Can anyone give me the quick laundry list of advantages/disadvantages for each?

As someone whos only significant experience is in PHP and Python, I hope I can be of some help. I started with PHP when was 13 or so. When I was about 18, I discovered Python, and haven't looked back since.

PHP is designed primarily as a web language. As such, it's pretty simple to get it up and running which is great for new web developers. The language itself, however, is pretty bad and programming concepts beyond syntax are better left to other languages. That said, I learned a lot with PHP and I think that dealing with it's idiosyncrasies and pitfalls has made me a better programmer overall.

Python, OTOH, is a general-purpose language that has recently gained popularity as a web language. It has greater applicability, but it's a little more difficult to get up and running on a web server. It's great for a new programmer, but not necessarily a new web developer. Since you already have a bunch of experience developing web apps, this is probably a non-issue.

We can debate advantages and disadvantages of the two languages all day. In the end, everyone is different and everyone has their own preferred language. Obviously, my language of choice is Python, Paul Graham is a LISPer, and I know someone who swears by PHP, even though he's used Python and Ruby/Rails. It doesn't matter. I say go ahead and give Python a shot. The worst that will happen is that you've added another tool to your toolbox.


Now more intelligently. It is very expressive (little code says a lot) and the code is really easy to read. If you already know how to program it takes a few hours to get your feet wet and from there the "batteries included" philosophy makes it easy to start writing real python.

More technically, my favorite features in no particular order:

- list comprehensions

- functions as first are first class objects (you can pass functions around just like any other piece of data)

- functional programming tools

- indentation determines scope (some dislike this, I don't like curly braces), and this makes the code look nice

- slice notation

- powerful native data structures (lists, dictionaries, sets)

- args and *kwargs

- awesome standard library

I could probably keep going...

- * * dictionary arguments

P.S. No two stars next two each other allowed on news.yc?

Python is certainly the more flexible of the two languages, but if you're really familiar with PHP you may be able to write your app faster in it and get it out there faster. But there's also long-term time savings to consider as well...

I haven't really done much in Python yet unfortunately, but I've worked quite a bit in Perl, PHP and Ruby, and personally I don't find any of them mind-blowingly different from one another, syntax aside. Some have more succinct syntax for looping and other things, but no major paradigm-shift IMO (like the one from imperative to functional).

Most of the complaints against PHP (just like MySQL) are about things that were solved years ago, but continue to linger on anyway. I like to think of PHP not so much as a language though, but more as a wrapper around C with memory management and a more flexible type system. Looking at PHP that way shows why many of its inconsistencies exist (e.g., in function names). It's also of the "structure is optional" philosophy, which requires more discipline to code well in.

Anyway, I think it comes down to figuring out whether it would save time now and later to use PHP or Python.

PHP doesn't have first class functions (and all of the stuff that sort of naturally flows from closures and all of the other nice bits that make dynamic languages so very nice to work with). It is a pretty dramatic difference between PHP and Python, Ruby, and Perl. Idiomatic usage of the latter three are, on the whole, similar to one another, but idiomatic usage of PHP is dramatically different. I think if you don't see "paradigm shift" differences, then you're writing PHP code in Perl and Ruby. In other words: You're doing it wrong.

PHP isn't really even in the same branch of languages as the three popular dynamic languages. It's like a fork off from C in the same way that chimps and humans shared a common ancestor 8 million years ago. So, one could say, "chimps are to PHP as humans are to Perl", if one wanted to be inflammatory...and in this case, one does. Both are pretty flawed as creatures go, but one flings poop and the other drives cars and builds roller coasters.

Fun is that PHP still lets you pretend it works functionally.





http://php.net/call_user_func_array (apply)

http://php.net/create_function (lambda)

PHP is a language that encompasses all useful things in all other languages. Which, I guess, makes it inferior.

Please don't call "create_function" a "lambda". That's a parody of anonymous function. You have to escape (\") your source code, function is registered in the global scope, and the only reference you get on it is... a string with generated, unique function name.

Yeah create_function is a half ass attempt for the use of lambda functions. I would not recommend using it.

You know that you have to supply the function by _name_ as a string?

I don't get what you're saying. aston did say pretend.

Once you have the function name (or an object method array) it can be stored in a variable with any name you want, passed around, etc. You can pretend it's a function all you want; you can check whether it seems like a real function with is_callable; and you can call it via call_user_func or call_user_func_array (this distinction made necessary because PHP lacks Python/Ruby *array unpacking syntax).

Somewhere I have a PHP class that lets you fake closure. You call Closure::Create($real_cb, $state_data) and it gives you a callback that, when called, calls $real_cb with $state_data plus all arguments that it was called with. And if $state_data is an array whose elements were assigned by reference, the 'closed-over' state is mutable.

So overall, it's a good pretense, even if foreach will always be faster than functional style.

Simulating closures? that seems pretty clever I've just recently integrated a functional extension into our private web application framework a few months ago. Perhaps we can share notes?

Well, since PHP by default reinterprets bare-strings as actual strings, you can just type the name without quotes, and things should still work. Until you define() a constant with the same name.

I do not mind the inconvenience of typing in quotes. I just do not like that function are not treated as first class citizens in this respect. There may be ways around this in newer versions of PHP, though.

By the way - can someone please try something like the following: $width = getimagesize($filename) [0];

The last time I checked, PHP threw a _Parser_Error_ for indexing an array that you just got from a function. Not even arrays feel like first class citizens.

(Pardon me, if this ward has been eliminated in the mean time. I just vividly remember losing some time hunting for a bug because of this 'feature'.)

Yeah, the [] operator works on a variable name, not on the variable itself. Kind of silly.

PHP is sloppy and messy, and say what you will, but the first time I tried writing something like the below code I definitely had one of those "Woah. That is cool." moments like first-time experience with lambdas:

   $a = 'var';
   $b = 'iable';
   $variable = 'var';
   echo ${$a.$b};
Useful? Sure it is:

   $filter = array("name", "email");
   foreach($filter as $v) $$v = $_POST[$v];

I did a lot of this when I built a form templating engine a few years back. When I came back to the code a year later, I had no idea what I was doing.

Python syntax is much cleaner, and with only one way to do things, it's almost always easier to read. I'm a Pythonista now.

Python‘s way of accomplishing this is as easy, although the use of `locals` should indicate that this isn’t generally something you should be doing:

    post = {'name': 'ijoshua', 'email': 'spam@example.com', 'extra': 'data'}
    filter = ['name', 'email']
    for k in filter: locals()[k] = post[k]
    print name, email

I've touched a nerve, it seems.

I was, of course, joking. Having a laugh at some of the obvious weaknesses in PHP, and pointing out that the other three popular dynamic languages go about things differently.

But, all but one of our world-facing websites are PHP applications (we run Wordpress, Joomla, FlySpray, and DokuWiki, our other wiki is the Perl-based TWiki). I'm actually a grudging fan of the language. It does a few things extraordinarily well, and I've been known to recommend that everyone building installable web applications ought to be writing them in PHP because of its pervasive availability.

Don't take it personally, folks. You're not going to convince me that create_function gives PHP first class functions (maybe if you squint a little), but you also don't need to convince me that it serves a niche very well. I don't have to like it, but I certainly have to use it, because it is currently the best tool for a large class of problems.

That's pretty funny! I got a good laugh out of the chimps image :)

I actually started in Perl about 8 years ago (well, before that it was just little Galaga and Snake clones in DOS :), so it's kinda my first love. But Perl was eventually too punk rocker for me...

I drank the Ruby kool-aid for a while too (mmm, pickaxe flavour :), and if I were to start fresh in a language without the framework I'm used to now, I would definitely be seriously weighing Ruby vs Python (or maybe finally get up on the functional languages).

Maybe I'm writing Ruby like PHP, but I probably write PHP more like Perl anyway. When I first came to PHP I was disgusted at ideas like "register_globals" and immediately ported CGI.pm and DBI over so I would have something sane to work with in PHP. This was long before PHP had its "superglobals" and even PEAR didn't exist yet back then.

That has always been my gripe with PHP. Perhaps by PHP8 we will begin to see things differently. That being said you just have to exercise some restraint so that the "monkey" behaves properly.

Given your comparison of PHP and C I assume you think of an aircraft carrier as a canoe with more guns and metal and stuff. ;-)

Not quite ;)

I just mean that really if you look at PHP's function list, it really is just a wrapper around C libraries. Many functions map 1-1 from the C lib to the PHP function. That's where it gets its string function names, many of the original database libraries were exactly that (which is why there was no built-in abstraction layer for so long), and you can look at GD or any other extension for more examples.

When you take that into consideration, you can see what the language designers were thinking in the decisions they made for PHP. They aren't necessarily the ideal choices, but the rationale does make sense.

I see what you're getting at, but I think it's better said like you did in the comment above. The standard library wraps a lot of C libraries. I however suspect that more came by way of Perl, which PHP was somewhat based on.

As a language, aside from the fact that they're from the same syntactic family, one is a compiled, low-level iterative language, the other is an (semi-) object oriented, dynamic, garbage collected, interpreted language. In terms of language features, it's a lot closer to the Python, Ruby, Perl clan than C.

Feature-wise, yes it's obviously closer to those, but what PHP did originally was wrap a Perl-esque syntax and dynamic environment (dynamic typing, interpreted code, GC, etc.) around C libraries as its "standard library". It's grown a lot since then, but the C connection still accounts for PHP's standard libraries, despite the big improvements in OOP and newer libraries in the last few years (SPL for example).

That is where many design limitations come from, and it's why PHP's standard library is still mostly just a collection of a million functions instead of something more OOP like the Python or Ruby :)

I'm a bit surprised you don't find any big differences between Ruby and PHP. But then again it might be that I haven't looked at PHP in the last 4 years.

Oh this seems interesting and I hope that unlike Reddit posts about PHP this will not degenerate into another flame post. So first off I would initially recommend using PHP as it is something you already know. Learning Python is cool(although I must confess I'm more of a Ruby user) but in the interest of getting something up and running quickly. And factor in that you already know PHP.

It would do you some good to learn a good PHP framework to rapidly build your app and get something out there immediately. A framework not only makes you look smart but it requires you to write code that does not merit you getting stabbed in your sleep. Ergo good PHP code.

Now we can all wax rhetoric that PHP does not support Functional idioms, brain dead functions, and name spaces. But in the interest of rapid prototyping and ease of deployment PHP comes first in mind. PHP frameworks now most notably Symfony(used by Yahoo to rewrite Delicious), CakePHP, Akelos, Kohana and my personal favorite CodeIgniter changed my opinion of PHP. You can easily abstract away logic using these frameworks. And they picked out some functions out of PHP's bewildering list of functions so that you have a solid base to work with.

So in a nut shell it's possible to write good PHP code but you have to exercise some discipline for it not to turn into spaghetti code.

Another reason you might want to carefully choose a language is the type of application you want for it. Let me explain, my company makes web based applications that customers can host within their corporate server. Now I don't want to waste much time trying to configure the server to run a specialize application. In fact I need something that can be installed and used right away in the shortest amount of time. So my choice of using PHP is more of a business decision as well.

So just weigh things out and ask yourself what do you wish to accomplish. Right tool for the right job.

edit: oh please consider reading this book http://www.manning.com/reiersol/ makes a good study on how to write good PHP code.


  - Easy to deploy on a webserver
  - Easy to integrate with HTML (good for small sites)

  - Not ugly
  - Real and consistent object system
  - Better documentation than PHP (even though PHP's is good)
  - More consistent libraries
  - BDFL (PHP is an unregulated mess)
  - Good C API
  - Excellent web frameworks
  - Excellent desktop app support
  - Very cross platform compatible
  - http://www.python.org/dev/peps/pep-0020/
  - It makes me smile

Just so you know my position, I'm a major advocate for Python. I love it and not long ago talked about my "fun" integrating it with Counter-Strike: Source at PyCon, introducing Python to thousands of gaming enthusiasts who have never coded befre.

Where can you point me to "better documentation than PHP"? This is a major difficulty for new people getting into Python-- the documentation is really quite poor and out-dated. My life would be much easier if the core Python documentation was nearly as good and organized as PHP or, even, MSDN.

What I really want is for every framework and language to have documentation as stellar as the user guide for the PHP framework Code Igniter: http://codeigniter.com/user_guide/

As a long time Python hacker, I'm used to using the interactive interpreter for my documentation needs (and then the source later). But that is absolutely not sufficient for newbies coming into Python-- they're lost in the arcane organization and formatting of the core Python documentation.

If you have a site that provides better core/comprehensive documentation than the official Python docs, let me know, as there are hundreds of Python scripters who would love it.

> Where can you point me to "better documentation than PHP"? This is a major difficulty for new people getting into Python-- the documentation is really quite poor and out-dated.

I disagree that the Python documentation is poor or out-dated. However, it is fragmented in what could be considered a confusing manner. I’ve often been searching for a particular piece of documentation, wondering if I should be looking in the tutorial, the library reference, or the language reference.

Years ago when I was switching from Perl to something else (I ended up on PHP mainly, and others where needed), I did look at Python but documentation was something that seemed lacking at that time. It just made me think at that point that Python wasn't going to be easy to find answers for when I run into problems. Sad to see that hasn't changed yet, it's been about 7 years since I really looked at it, and has gained some huge traction recently too.

I find this comparison biased towards python.

I know Python's indentation is a big turn off to most people coming from another language; it seems almost invasive of the interpreter to pay attention to whitespace. But you get used to it, and it becomes quite nice.

I had the opposite reaction when I first learned Python--I thought forced indenting was genius. It's something that should be enforced in every language because it makes the program dramatically easier to read. One problem I've noticed with Python code online is when leading and trailing whitespace is stripped from code examples (e.g. posting code to a forum). The code just stops making sense all of a sudden.

The syntax that you hate will grow on you. If you're like me, at some point you'll wonder why other languages do not use whitespace effectively. It may be annoying at first, but when you revisit code later it makes it much more readable imho. If you're referring to other syntactic details, many grow on you, but luckily there is a fair amount of flexibility in coding style.

I developed my first web app last year. I decided to use python as I already knew it. I didn't find python got in the way at all. In fact MOST of the code for the site is in preprocessing data and python worked equally well for that as it did serving content. PHP developers I've spoken to say that while PHP could have done the processing, python was a better choice.

Just thought I'd mention that.

good luck.

I found PHP to be easier to deploy. It might (because I'm not sure how much memory Python apps with mod_python or mod_wsgi really take) also be a better choice if you're making multiple sites and don't have a lot of memory on your server (e.g., 256MB VPS) since it doesn't take up too much memory.

I find this to be a useful assessment of PHP:


for me (compared to php) python is easier to debug and it's easier to organize and abstract your logic.

not to mention I think there are cooler libraries out for python than for php, and it's more versatile (desktop apps, utility scripts) instead of just being web-centric

Thanks for all of the comments. doubleplus' link was particularly helpful. I should clarify that I already have a prototype in PHP and was thinking about switching to Python for the beta/release version if it seems worth it.

It depends what you want to do with it ultimately. I use both - generally PHP for web-based front-ends and Python for heavy lifting (crawlers, text processing etc)

Also, consider that Python has a lot more non-web uses that PHP does. You'll derive more benefit from Python proficiency than PHP.

Google App Engine

Python: +2

Well, personally I'm going to stick with AWS for now. Firstly out of loyalty, but secondly because Amazon has great support. Ok, ok - Google have brought this out and are focused on Python for now, but that shouldn't be a reason :) I use Python on AWS btw

Learn it and find out ;)


Sigh. I cannot in good conscience support a language in which an indent has semantic value. It's just not right.


What about Ruby?

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact