OpenCart – PHP Array Study

This will be a topic of discussion for the programmer that wishes to venture out on his/her own to customize their own Open Cart store. The Open Cart framework in fact is free to use and is a great one to learn on. One simply can’t build a successful store without knowledge of PHP arrays. Not only are array’s used very commonly throughout most PHP developments, they are used very heavily within the Open Cart framework.

What is an array?

An array is a special variable, which can hold more than one value at a time. It can hold many values and many different TYPES of values. You can access the array at any time even any value of the array by referring to an index number….or, you can refer to an actual value. Array’s are considered extremely powerful in the coding world because they unlock doors that otherwise would stay locked when it comes to rich application development. Array’s are also easily stored in database systems and can be reused later on at any time.

Declaring an array

In the language of PHP declaring an array is as easy as this: $my_value = array(); Now we have made the variable $my_value an array that is ready to be used. $my_value will remain empty until we apply a value to it.

Empty an array

You can RE-EMPTY the array at any time by declaring it again in the way we did above. There actually are two ways to empty an array. One, by declaring it $my_value = array(); and two, by un-setting it like this: unset($my_value);

Add to an array

To add to an array you simply have to write it like this: $my_value[] = “value”; Here we are adding a string as a value but you can also add integers, floating numbers, and even other array + more. Again arrays can hold many types of data which makes them invaluable. When adding to an array you can also alter the natural key setting by adding your own KEY when adding a value. Note, this can only be done in certain formats. $my_value[$key_value] = “value”; You can keep adding to the array and the array will keep growing so as long as it is not unset. The Opencart shopping cart is a great example of an array that keeps building upon itself and actually uses both KEY and VALUE to hold two values. To find where Opencart first declares the shopping cart array just open up this file system/library/cart.php and locate the following code:

if (!isset($this->session->data['cart']) || !is_array($this->session->data['cart'])) {
      		$this->session->data['cart'] = array();
    	}

Here you have an isset check on the cart session array where if it is NOT set, then set it by doing this: $this->session->data['cart'] = array(); Now to find where the Opencart actually adds to this array just search for the following function:

public function add($product_id, $qty = 1, $option = array()) {
if (!$option) {
$key = (int)$product_id;
} else {
$key = (int)$product_id . ‘:’ . base64_encode(serialize($option));
}
if ((int)$qty && ((int)$qty > 0)) {
if (!isset($this->session->data['cart'][$key])) {
$this->session->data['cart'][$key] = (int)$qty;
} else {
$this->session->data['cart'][$key] += (int)$qty;
}
}$this->data = array();
}

In red I highlighted the arguments being passed to the function by the control. The arguments in the control look like this: $this->cart->add($this->request->post['product_id'], $quantity, $option) Passing arguments is a nifty way to distribute data from one function to the next and in this case we are dealing with the product_id, quantity, and options (if any). Let’s look closely at the first part of the function:

if (!$option) {
$key = (int)$product_id;
} else {
$key = (int)$product_id . ‘:’ . base64_encode(serialize($option));
}

What you are seeing is: IF NO OPTION(s) variable $key = $product_id }ELSE{ variable $key = STRING. This string is very important; it holds the product_id and the entire option array, concatenated together by a ‘:’. You will notice the $option variable is base64_encode(serialize(). Why do this? This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean. Likewise, the serialize function is designed to keep array’s intact so you can use them again later.

And now the last part of this function:

if ((int)$qty && ((int)$qty > 0)) {
if (!isset($this->session->data['cart'][$key])) {
$this->session->data['cart'][$key] = (int)$qty;
} else {
$this->session->data['cart'][$key] += (int)$qty;
}
}$this->data = array();

And here is the function with comments to explain what is happening:

if ((int)$qty && ((int)$qty > 0)) {

//validation that quantity is greater than 0 and correct form

if (!isset($this->session->data['cart'][$key])) {

//if the product DOESN’T exist in cart with matching properties/options. We are using the variable $key to run the check

$this->session->data['cart'][$key] = (int)$qty;

//add product to cart array (new product)

} else {

$this->session->data['cart'][$key] += (int)$qty;

//this is if product DOES exist in cart with matching properties/options //Add another of the same to change quantity. This is done by (+=)
}
}

In short, we add a new item to the cart if it doesn’t already exist OR we increase the quantity of an existing item because the system has detected an identical match with the same options/properties. If you remember that we started with the session array: $this->session->data['cart'] as an empty array. Now we are filling the array with a KEY and a VALUE. The KEY is $key and the VALUE is the quantity, so it is declared here: $this->session->data['cart'][$key] =

Now we have showed you a good example of how Opencart uses both key and value in an array to pass information.

Storing an array

PHP offers a wonderful way to store arrays. This method is called serialization. The function serialize() allows you to compact the array information into a storable format within a TEXT AREA in a database table. Once it is stored you can then access it at any time by running the unserialize() function which puts it back to how it was. To sum it up, serialize generates a storable representation of a value. This is useful for storing or passing PHP values around without losing their type and structure. To be honest you really don’t know how powerful this feature can be until you start developing. I’ve developed many applications that store very large array data with serialize() and accessed later via unserialize().

Accessing an array and it’s values

Now that we know how to create an array and store that array, let’s learn how to iterate through the array to display information. There are a few ways to access an array to display it’s information but in this article we will go over the two most popular in PHP. First we will start with the most popular function foreach() which is probably the most used. The foreach() function is used many times in Opencart so we will just take a snippet of one page to demonstrate as an example. We’re going to show you the foreach()  function in the .TPL but also how the variable is set up in the control. Open the following file in your latest 1.5.6 Opencart directory: catalog/controller/product/category.php and find the following code:

			
				$this->data['products'][] = array(
                    'product_id'  => $result['product_id'],
                    'thumb'       => $image,
                    'name'        => $result['name'],
                    'description' => utf8_substr(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8')), 0, 100) . '..',
                    'price'       => $price,
                    'special'     => $special,
                    'tax'         => $tax,
                    'rating'      => $result['rating'],
                    'reviews'     => sprintf($this->language->get('text_reviews'), (int)$result['reviews']),
                    'href'        => $this->url->link('product/product', 'path=' . $this->request->get['path'] . '&product_id=' . $result['product_id'] . $url)
                );

The code you found is the creation, and filling of a multidimensional array called $products. Somewhere above in on that page you will see the array being created like this $products = array(); and with the code you just found….it is filled with different elements.

'product_id' => $result['product_id']

This shows a key value of product_id and it’s value of $result['product_id']. In the .TPL you will see how the key is used to echo the actual value in the multidimensional array. Now open the following file: catalog/view/theme/default/template/product/category.tpl and find the following code:

<?php foreach ($products as $product) { ?>
    <div>
      <?php if ($product['thumb']) { ?>
      <div class="image"><a href="<?php echo $product['href']; ?>"><img src="<?php echo $product['thumb']; ?>" title="<?php echo $product['name']; ?>" alt="<?php echo $product['name']; ?>" /></a></div>
      <?php } ?>
      <div class="name"><a href="<?php echo $product['href']; ?>"><?php echo $product['name']; ?></a></div>
      <div class="description"><?php echo $product['description']; ?></div>
      <?php if ($product['price']) { ?>
      <div class="price">
        <?php if (!$product['special']) { ?>
        <?php echo $product['price']; ?>
        <?php } else { ?>
        <span class="price-old"><?php echo $product['price']; ?></span> <span class="price-new"><?php echo $product['special']; ?></span>
        <?php } ?>
        <?php if ($product['tax']) { ?>
        <br />
        <span class="price-tax"><?php echo $text_tax; ?> <?php echo $product['tax']; ?></span>
        <?php } ?>
      </div>
      <?php } ?>
      <?php if ($product['rating']) { ?>
      <div class="rating"><img src="catalog/view/theme/default/image/stars-<?php echo $product['rating']; ?>.png" alt="<?php echo $product['reviews']; ?>" /></div>
      <?php } ?>

Now we get to the foreach() function that looks through the array we established in the category.php control file. It starts with this line:

<?php foreach ($products as $product) { ?>

Above I mentioned that the key value would be being used and here you can see it plain as day: <?php echo $product['price']; ?>

Useful Array Functions

  • array_change_key_case — Changes the case of all keys in an array
  • array_chunk — Split an array into chunks
  • array_column — Return the values from a single column in the input array
  • array_combine — Creates an array by using one array for keys and another for its values
  • array_count_values — Counts all the values of an array
  • array_diff_assoc — Computes the difference of arrays with additional index check
  • array_diff_key — Computes the difference of arrays using keys for comparison
  • array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison
  • array_diff — Computes the difference of arrays
  • array_fill_keys — Fill an array with values, specifying keys
  • array_fill — Fill an array with values
  • array_filter — Filters elements of an array using a callback function
  • array_flip — Exchanges all keys with their associated values in an array
  • array_intersect_assoc — Computes the intersection of arrays with additional index check
  • array_intersect_key — Computes the intersection of arrays using keys for comparison
  • array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison
  • array_intersect — Computes the intersection of arrays
  • array_key_exists — Checks if the given key or index exists in the array
  • array_keys — Return all the keys or a subset of the keys of an array
  • array_map — Applies the callback to the elements of the given arrays
  • array_merge_recursive — Merge two or more arrays recursively
  • array_merge — Merge one or more arrays
  • array_multisort — Sort multiple or multi-dimensional arrays
  • array_pad — Pad array to the specified length with a value
  • array_pop — Pop the element off the end of array
  • array_product — Calculate the product of values in an array
  • array_push — Push one or more elements onto the end of array
  • array_rand — Pick one or more random entries out of an array
  • array_reduce — Iteratively reduce the array to a single value using a callback function
  • array_replace_recursive — Replaces elements from passed arrays into the first array recursively
  • array_replace — Replaces elements from passed arrays into the first array
  • array_reverse — Return an array with elements in reverse order
  • array_search — Searches the array for a given value and returns the corresponding key if successful
  • array_shift — Shift an element off the beginning of array
  • array_slice — Extract a slice of the array
  • array_splice — Remove a portion of the array and replace it with something else
  • array_sum — Calculate the sum of values in an array
  • array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_udiff — Computes the difference of arrays by using a callback function for data comparison
  • array_uintersect_assoc — Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
  • array_uintersect — Computes the intersection of arrays, compares data by a callback function
  • array_unique — Removes duplicate values from an array
  • array_unshift — Prepend one or more elements to the beginning of an array
  • array_values — Return all the values of an array
  • array_walk_recursive — Apply a user function recursively to every member of an array
  • array_walk — Apply a user function to every member of an array
  • array — Create an array
  • arsort — Sort an array in reverse order and maintain index association
  • asort — Sort an array and maintain index association
  • compact — Create array containing variables and their values
  • count — Count all elements in an array, or something in an object
  • current — Return the current element in an array
  • each — Return the current key and value pair from an array and advance the array cursor
  • end — Set the internal pointer of an array to its last element
  • extract — Import variables into the current symbol table from an array
  • in_array — Checks if a value exists in an array
  • key_exists — Alias of array_key_exists
  • key — Fetch a key from an array
  • krsort — Sort an array by key in reverse order
  • ksort — Sort an array by key
  • list — Assign variables as if they were an array
  • natcasesort — Sort an array using a case insensitive “natural order” algorithm
  • natsort — Sort an array using a “natural order” algorithm
  • next — Advance the internal array pointer of an array
  • pos — Alias of current
  • prev — Rewind the internal array pointer
  • range — Create an array containing a range of elements
  • reset — Set the internal pointer of an array to its first element
  • rsort — Sort an array in reverse order
  • shuffle — Shuffle an array
  • sizeof — Alias of count
  • sort — Sort an array
  • uasort — Sort an array with a user-defined comparison function and maintain index association
  • uksort — Sort an array by keys using a user-defined comparison function
  • usort — Sort an array by values using a user-defined comparison function

 

If you can master arrays, you can do anything. The power is very unlimited. Without the power of Array’s, Opencart would not be what it is and what it has become today.

Looking for quality OpenCart Hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , , , , | Posted under OpenCart | RSS 2.0

Author Spotlight

Joe Stenhouse

Joe Stenhouse

I am a web application developer that specializes in PHP, JAVASCRIPT, MYSQL, HTML, and CSS. We manifest exciting potentials within the world wide web through means of innovation.

One Comment on OpenCart – PHP Array Study

  1. swed says:

    Thanks Joe, I much enjoy reading your blog posts. English isn’t my native language but I find your writing quite easy to follow and understand. Besides that, I think you pick interesting topics too. Your statement about “the power of array’s” and the current stand of OpenCart might be correct from a programming point of view but I’m absolutely convinced that any other owner of the OC code that embraced the true meaning of open source would take OC to an incomparably higher level.

Leave a Reply

Your email address will not be published. Required fields are marked *


5 − 4 =

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>