r/PHP • • Jun 29 '14

Stop abusing arrays in PHP

http://nomad.so/2014/06/stop-abusing-arrays-in-php/
0 Upvotes

45 comments sorted by

27

u/dont_ban_me_please Jun 29 '14

Oh fuck this guy. PHP arrays are powerful and flexible and simple to create and use. They just get the job done. That's what PHP does, it just fucking gets the job done. That's what has made it so popular and that is why this guy is completely wrong.

15

u/darkhorsehance Jun 29 '14

Just because a tool is powerful, flexible and simple doesn't preclude it from abuse. Getting the job done doesn't imply engineering best practices. Often times, for the flexibility gained, important things like maintainability and testability are sacrificed. Not to mention you lose the power of encapsulation (arrays have no way of expressing behavior) and polymorphism (arrays are of type array) which is essential for quality OOP. Don't get me wrong, when used in the right context arrays are a perfectly valid tool, especially in PHP. The examples highlighted in the OP's article are commonly found in PHP and it's a shame. It makes the community look like amateurs. This is especially a shame for the folks in the symfony/laravel/hhvm communities working hard to make the community a better place.

1

u/mattaugamer Jun 29 '14

Just because a tool is powerful, flexible and simple doesn't preclude it from abuse.

Quite the opposite actually. "I have such a good hammer! And look at all these nails!"

0

u/[deleted] Jun 30 '14

[deleted]

1

u/mattaugamer Jun 30 '14

No, I am agreeing, saying it does the opposite of precluding. It makes it even more likely. Useful and powerful tools are more likely to be abused.

-1

u/[deleted] Jun 29 '14

Exactly!

-1

u/i_make_snow_flakes Jun 29 '14

It makes the community look like amateurs.

How dare you call me an amateur. I have read about SOLID principles, like last week and I can talk about it for hours now. I attend Laracon, Zendcon and what not. I can even agree with framework creators and upvote their every comment even if that is "Great work" or "Kudos". And last but not least, I use Phpstorm, which is like the best php IDE ever! /s

-1

u/dont_ban_me_please Jun 29 '14

Dern you and your reasonable response :)

I can agree that it's all situational. No problem. I'm not going to use or not use a data structure based on how it "makes the community look like amateurs" though.

6

u/Salamok Jun 29 '14

I don't disagree with everything he said but I feel an extremely strong desire to read an article on all the ridiculous instances of cramming array data into an object for oops sake.

0

u/[deleted] Jun 30 '14

[deleted]

1

u/Salamok Jun 30 '14

Maybe a long article on hash tables?

4

u/jen1980 Jun 29 '14

And with more and more JSON data out there that you have to consume, multidimensional array use is increasing.

11

u/i_make_snow_flakes Jun 29 '14

Arrays are not evil but should only be used when a collection of data has no associated behaviour.

Does that sentence make any sense to you?

4

u/itsnotlupus Jun 29 '14

Implying commenters read the article

3

u/diolemo Jun 29 '14

The conclusion is the first place he really says that.

One sentence near the top of the article would have made it a lot better.

1

u/dadkab0ns Jun 30 '14

PHP arrays are powerful and flexible and simple to create and use.

Simple to create and use, yes. Flexible, sure. Not powerful though. By definition they are behavior-less packages of data.

It's silly to use an array as a data container when you should be using an object to get TRUE power and flexibility out of it.

I can't count the number of arrays like this that I've refactored out into objects to drastically simplify working with the data that they contain.

There are plenty of situations where using an array is fine, but not when it makes your code harder to maintain or makes you repeat yourself a lot.

Passing an array of data into a method or other class as an argument makes it impossible to validate for integrity. Properly using objects saves you from that problem. If I have some client code that wants to consume data that represents a comment, passing that data through as a Comment object instead of an array will allow me to guarantee that the data is complete and safe to work with, rather than a bunch of isset() or null checks.

-2

u/[deleted] Jun 29 '14

it just fucking gets the job done.

How very short term that sounds, you are part of the problem and why PHP and it's devs have a bad name.

The entire point of this article is to realise you'll be maintaining this code for years. 'Just getting it done' does not cut it for professional long term development.

1

u/callcifer Jun 30 '14

The fact that this is the top comment speaks volumes about the average PHP developer...

-5

u/yusit Jun 29 '14

Agrred, Where's my pitch fork, I just had it....

7

u/ivosaurus Jun 29 '14 edited Jun 30 '14

If this was another language, they would be dictionaries, or hashes, or maps, and it would be a perfectly normal use of them.

The problem is the name PHP gave to this data structure in the first place. It's hardly the implementation one would normally associate with what's referred to as an "array" in most languages / data structures courses or CS in general.

If there's semantic behaviour that's useful to associate to the array's (/dictionary's) contents, then yes, it can be a great idea to map them onto objects, but otherwise keeping them in a structured recursive format is just fine; a lot of data looks like this anyway.

In short, you may as well say that JSON is an evil data transport format, because that's probably the most common expression of this sort of data seen in this day and age.

1

u/Salamok Jun 30 '14

Oh shit I think you just prompted the guy to write a 5 page article on why SOAP is the shit and JSON is for 15 year olds.

15

u/rq60 Jun 29 '14

TLDR: Arrays are evil, let me show you how to use Iterators!! That return an ArrayIterator...

15

u/atw527 Jun 29 '14

My problem here is that arrays are always used where objects should be!

Stopped reading the article at that point.

2

u/MorrisonLevi Jun 30 '14

I started skimming at this point.

To sum up my thoughts: if you are dumping JSON from a database then use arrays and json_encode them; else consider using classes.

5

u/Xinil Jun 29 '14

I would have appreciated more examples of an array turned in to an object. The example he used were more or less psuedo code and didn't implement what he said it could. I use arrays a lot, probably too much, so I'd love concrete examples for everyday problems.

8

u/willmorgan Jun 29 '14

What this man is advocating is essentially replicating that same structure, but putting a load of classes on top of it to make it more complicated.

At a very primitive level, "abusing" arrays in the article's example is simpler and less time consuming than this method. Only in large applications is it worth going to the extreme of creating a collection / iterator class per "dimension" of the array... and at that point, a good programmer would consider alternatives to managing so much data at once, anyway.

In fact, in a way, this article is a bit of a straw man - doesn't this gigantic array look more like a JSON document to you? Something you'd get back from an API, perhaps? Hmm.

3

u/chuyskywalker Jun 30 '14

What this man is advocating is essentially replicating that same structure, but putting a load of classes on top of it to make it more complicated. Only in large applications is it worth going to the extreme of creating a collection / iterator class per "dimension" of the array

To expand:

In a simple, narrow view, all this extra code is more complicated. Implementing it takes time, a not-small bit of extra code, and is a more advanced topic.

That said, when your codes base starts getting larger, having clear interfaces/methods on collections (and ultimately getters/setters on the returned instances) is far easier for a larger team to develop upon. Basically, there's very little room for error -- if you call a wrong method() PHP will fatal you. If you call a bad $array['thing'] you get a plain notice which, sadly, can be pretty easy to, well, not notice). And, of course, if you have an IDE you get full code completion which makes is bloody obvious that you've made a code error (red squiggle underlines) and even easier down the road if you, god forbid, ever need to refactor your data objects. (IE: Have fun searching for that array key of "config" throughout a codebase.)

For your small home grown project, butcher arrays as deep as you want. If you want multiple people to work on a codebase day in and out, put better structure behind your data objects -- don't make me have to alt tab to the magic list of what's in the array every time I can't recall what library 56 of 738 wants me to call person value. (Was that person? Or user? Hrm, maybe userInfo? Ugh...)

0

u/-Mahn Jun 29 '14

It's not just simpler and less time consuming, a simple multidimensional array is also much more efficient than a set of objects and a collection both in terms of memory and performance. This rarely makes a significant difference unless the data is huge, but still.

3

u/aichibuchi Jun 29 '14

Any application sufficiently large for that to actually make a performance difference needs to be well-structured, which probably means not using massive multidimensional arrays, right? Also, I'm pretty sure performance is incredibly inexpensive these days. Certainly cheaper than spending engineering time maintaining something poorly structured.

2

u/00Davo Jul 09 '14 edited Jul 09 '14

Reiterating this snippet's simplicity

$stockedFish = $ponds->getTotalStockNumber();

relative to something like

foreach ($ponds as $pond)
{
    if (isset($pond["fishBreeds"]))
    {
        foreach ($pond["fishBreeds"] as $breed)
        {
            if (isset($breed["number"]))
            {
                $stockedFish += $breed["number"];
            }
        }
    }
}

seems, well, disingenous. getTotalStockNumber() won't just magically work without being implemented somewhere, and its implementation is almost certainly going to involve foreach loops much like those in the second sample.

By the same token, you could as easily make a comparison like this:

With OO design, you often end up with dozens of extraneous classes to implement something that would be straightforward in procedural code. Here's what would be a simple calculation, implemented in classes:

class PondsCollection implements IteratorAggregate {
  private $collection = array();

  public function getIterator() {
    return new ArrayIterator($this->collection);
  }

  public function add($pond) {
    $this->collection[] = $pond;
  }

  public function getTotalStockNumber() {
    $sum = 0;
    foreach($collection as $pond) {
      $sum += $pond->getTotalStockNumber();
    }
    return $sum;
  }
}

class StockDataCollection implements IteratorAggregate {
  private $collection = array();

  public function getIterator() {
    return new ArrayIterator($this->collection);
  }

  public function add($stockdata) {
    $this->collection[] = $stockdata;
  }

  public function getTotalStockNumber() {
    $sum = 0;
    foreach($collection as $fish) {
      $sum += $fish->number;
    }
    return $sum;
  }
}

class Pond {
  public $name;
  public $size;
  public $pegs;
  public $amenities;
  public $fishBreeds;

  public function getTotalStockNumber() {
    return $fishBreeds->getTotalStockNumber();
  }
}

class StockData {
  public $name;
  public $number;
  public $date;
}

Wouldn't it be a lot simpler to do this?

$stockedFish = getTotalStockNumber($ponds);

Of course, both comparisons are equally misleading, and in fact neither actual implementation is significantly more complex. The same fundamental techniques of functional abstraction are applicable regardless of paradigm here.

1

u/moonpi3 Jun 30 '14

I like the idea of avoiding the use of arrays as data types. I usually turn these into objects. Otherwise, I use Dictionary, Enum, Collections and Tuple classes in PHP when appropriate. It's a little more overhead, but it's easier code to maintain.

1

u/DancesWithNamespaces Jul 02 '14

I get the point you're trying to make, but I don't think you quite grasp the entire concept you're trying to explain either.

Arrays are often used when classes would be better served for the purpose, but sometimes arrays are a better choice in the scope of the function they're being used in.

Your entire article could have been replaced with the sentence from your conclusion: "Arrays are not evil but should only be used when a collection of data has no associated behaviour." and made much more meaningful sense.

0

u/bulbishNYC Jun 29 '14

Guys in their teens are wannabe hackers - the more unreadable my code the better. Guys in their 30's are seasoned pros - keep everything simple a retard can read & maintain it. 20's - middle ground, pattern over-engineering, pimp-my-github phase.

2

u/mattaugamer Jun 29 '14

I'm 37. Approaching about 15 years in this industry. And I think you're full of shit.

More specifically, I think you're partially right. Older, senior devs care more about maintainability. But the point of what this article is saying is to advocate more maintainable coding.

In my experience older developers fall into two camps: seasoned veterans who know the value of maintainability while using appropriate abstractions and patterns, and ossified older devs who don't want to learn new things and refuse to improve their skills.

Be careful not to be the latter, while thinking you're the former.

1

u/zendopeace Jun 29 '14

Pretty much this. Real programmers who have been out there and doing real work dont care so much for patterns and the latest buzz word, we just get it done. Arrays are useful, we use them. Objects are useful, we use them too. Theres no point getting so emotional about it all.

-1

u/weevil_of_doom Jun 29 '14

They're easy and useful. This guy needs to stuff it.

0

u/adrianmiu Jun 29 '14

"Arrays are not evil but should only be used when a collection of data has no associated behaviour." On the other hand $user->getName() is not a behaviour.

The reason people use objects when they can use arrays is that the IDE's autocompletion makes it so you don't need to memorize the structure of the array.

2

u/[deleted] Jun 30 '14

Being able to enforce an interface is a good enough reason for me. I couldn't care less about IDE sorcery.

-6

u/jasonlotito Jun 29 '14

ITT: PHP script kiddies complaining about someone bad mouthing their arrays.

2

u/i_make_snow_flakes Jun 30 '14

The downvotes you are getting confirms your point.

0

u/Thatonefreeman Jun 30 '14 edited Jun 30 '14

Yes lets take a simple data model and make it needlessly more complicated by adding layers to it. Know what the learning curve is of an array? Zip. None. Look at it and you know it. You're going to spend more time writing up your classes than you will building a simple function to parse arguments into an existing structure. Plus littering your code with objects will only serve to lengthen your already short time with educating new developers on your code.

Arrays are meant to be "abused" because that's one of PHP's greatest features. There is a time and place for arrays and objects of course, its subjective, but one should not conduct a witch hunt on every array in existence to justify itself.

1

u/ForeverAlot Jun 30 '14

This is the hare-argument to OP's tortoise-argument.

-2

u/stesch Jun 29 '14

I guess Lerdorf's talk about OO being slow had made a huge impression on PHP users.

1

u/[deleted] Jul 07 '14

This is rich coming from Lerdorf. PHP is one of the worst designed, poorly performing languages ever.

9

u/jasonlotito Jun 29 '14

I've never seen a case were OO was the bottleneck. You literally have to remove networking from the equation to make it have any impact.

1

u/stesch Jun 30 '14

I think the problem in Lerdorf's talk was that he was trying big frameworks. And profiled and optimized the absolute shit out of it. Including tracing Apache httpd.