CodeIgniter: Two Ways of Writing Arrays

There are two ways of writing arrays in PHP. We will use CodeIgniter in this example. Since CodeIgniter is a MVC framework, we will look at code in models. Assuming that a form is being submitted, and data is saved to the database. In this example, we will use a function called ‘add_entry.’

The add entry function is empty at the moment.

function add_entry() {
}

We will now add post data to our function. In this example, we will use the ‘url’ and ‘anchor’ fields. To sanitize, we set both values to TRUE. We assign it to a variable called $data in an array.

function add_entry() {
$data->url = $this->input->post(‘url’,true);
$data->anchor = $this->input->post(‘anchor’,true);
}

We will now insert data to a database table called ‘bookmarks.’

function add_entry() {
$data->url = $this->input->post(‘url’,true);
$data->anchor = $this->input->post(‘anchor’,true);
$this->db->insert(‘bookmarks’, $data);
}

The other way of writing an array is this:

function add_entry() {
$data = array(
‘url’ => $this->input->post(‘url’,true),
‘anchor’ => $this->input->post(‘anchor’,true));
$this->db->insert(‘bookmarks’, $data);
}

Essentially, both are the same. Somehow, I prefer the second. It seems cleaner somehow. It seems like, I only have to deal with a single variable called $data. What’s your preferred method?

6 thoughts on “CodeIgniter: Two Ways of Writing Arrays

  1. The first method you use actually creates an object (stdClass). You can see this by using var_dump($data); after setting the values.

  2. Thanks for pointing it out that it is an stdClass object. CodeIgniter doesn’t seem to mind either one. I was just wondering if there are drawbacks to using one from another. Until I saw this article. Objects are way slower. Arrays are definitely the way to go.

  3. Creating objects on the fly has it’s place, but rarely do I do it, arrays are much lighter on memory, and faster and have just as many options for manipulation.

    That said there are places for objects, especially when you need form validation against a particular set of data. Loading an object and loading the data into the object are a much better option than running validations on each input.

  4. I think the confusion for most people including me is the difference between this:

    $data->url = $this->input->post(‘url’,true);
    $data->anchor = $this->input->post(‘anchor’,true);

    and this:

    $data['url'] = $this->input->post(‘url’,true);
    $data['anchor'] = $this->input->post(‘anchor’,true);

    were the first one is an object and the second an array. I can see how easy it is to confuse the two.

Comments are closed.