Arrays or objects in PHP?

Warning! This post is either deprecated or outdated.

I assumed until a couple of days ago that objects are way better then arrays, but let’s take a closer look into that.

As objects are an instance of a class you can always know what type of data is inserted in the object, when trying this in an array you quickly get in to problems, for example:

$testcase = array();
$testcase["Name"] = "testcase";
$testcase["value"] = 20;

When doing this in objects, you can split it up very easy like so:

$testcase = new testcaseObject();

I guess you see my point….

When using huge amount of data though, arrays seem to have the upper hand in memory usage so that can count as an advantage.

When we create a query to get some data from a database that returns us multiple rows, the best thing you can do is make an array of objects. Like this:

while( statement ) {

$id = $row->categoryId;

// If category doesn't exist, we create him, else do nothing
if (!isset($category[$id])) {
$category[$id] = new testcaseCategory ();

// Create testcaseObject
$testcase = new testcaseObject();

// Add testcaseObject to testcaseCategory.


Have fun with it.

By the way, if you found a typo, please fork and edit this post. Thank you so much! This post is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.


Fork me on GitHub