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

 

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

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 *