Putting Arrays To Work – Shopping Cart (php)


Hello! Today, I want to use arrays to improve our shopping cart and find out more about them as we go a long! This post is going to be split into two: Part 1 and 2. You want read them in parts or in full. There are basically two types of arrays in PHP: numerically indexed arrays – where indices start at zero by default and non-numerically indexed arrays – where the keys can be set to whatever you deem meaningful. Let us start with numerically indexed arrays:

#Using the items from our store (oil, tires & spark plugs)
#We can create an array like this:
$products = array(‘Tires’, ‘Oil’, ‘Spark Plugs’);
#this creates a $products array containing 3 items
#just like echo, array() is a language construct rather
#than a function.

#You can use range() to create an array of ascending numbers.
$numbers = range(1, 10); # 1….10
#Add a 3rd param to set the step size between numbers:
$odds = range(1, 10, 2); #array of odd numbers from 1 to 10

#You can also use letters with range like so:
$letters = range(‘a’, ‘z’);


Accessing Array Contents

To access the content of an array, you need the variable name and an index or key. The index is placed inside square brackets: Let us take a quick look here:

#Using our $products array, we can easily:
$products[0] #Tires
$products[1] #Oil
$products[2] #Spark Plugs

#As you can see, element zero is the first element in the array
#To change elements in our array, we do this:
$products[0] = ‘Fuses’; #replaces Tires with Fuses
$products[3] = ‘Fuses’; #adds Fuses to the array

#Now we can print out everything in our array like so:
echo “$products[0] $products[1] $products[2] $products[3]”;

#You can also create the $products array on the fly:
$products[0] = ‘Car’;
$products[1] = ‘Cow’;
$products[2] = ‘Tablet’; #love a tablet!

#If $products array does not exist, the first line creates it!
#As you add elements, the array is dynamically re-sized!

Using Loops To Access Array Data:
Because arrays of this kind are indexed using a sequence of numbers, you can easily use a for loop to display contents


#Consider this example:
#We can easily print out the content of the array by:
for($i = 0; $i < 3; $i++){
echo $products[$i].” “;
#I just added a space there to clean things up a bit!
#Now using a foreach to print out everything!
foreach($products as $product){ #foreach($array as $variable)
echo $product.” “;
#Now you have a choice to make – which loop to use and that
#totally depends on your taste! Freedom is yours!

Arrays With Different Indices:
Instead of letting PHP assign a value of 0, 1 or 2 to our array, we can create our own indices! Let us take a look at how to do this below:

#Using Non-numerical indices:
$prices = array(‘Tires’ =>50, ‘Oil’ => 100, ‘Spark Plugs’ => 40);
#The product names are keys and prices are values.
#In between them are an equal sign (=) and a greater than (>) sign

#Let us access the contents of our $prices array
#Like before, we need the variable and a key

$prices[‘Tires’], $prices[‘Oil’], $prices[‘Spark Plugs’]

#Alternatively, we can create the above array like this:
$prices = array(‘Tires’ =>100);
$prices[‘Oil’] = 15;
$prices[‘Spark Plugs’] = 200;

#Yes, another way to do the same thing is by doing this:
$prices[‘Tires’] = 100;
$prices[‘Oil’] = 50;
$prices[‘Spark Plugs’] = 14;

Using Loops With Non-Numerically indexed arrays:
I figured you might have asked yourself whether you could do the same thing as you did earlier using for loops to print out content! Let us take a quick look here!

#You cannot use a simple counter here because the indices are not
#numbers, and that means we have to use a foreach loop! Cool!
#let us print out key : value pairs from our array
foreach($prices as $key => $value){
echo $key.” – “.$value. “<br />”;

#You can also use a while loop and an each() construct like so:
while($element = each($prices){
echo $element[‘key’];
echo ” – “;
echo $element[‘value’];
echo “<br />”;
#The above while loop will result in something like this:
#———-|Tires – 100 |———————-#
#———-|Oil – 10 |———————-#
#———-|Spark Plugs – 14 |———————-#

#Let us go rogue here and make this while loop look cooler:
while(list($product, $price) = each($prices)){
echo “$product – $price<br />”;
#Using list() construct helps to split an array into a number
#of values. So, we separate 2 values given to us by the each()
#construct like above.
#Since the each() construct keeps track of the current element,
#we simply use reset($prices) to set the current element back
#to the start of the array!

Array Operators
I am going to list Array operators and briefly describe what they do:

#–| Operator | Name | Example | Result |
#–| + | Union | $a + $b | Array $b appended to $a |
#——————————— | Any key clashes not added|
#–| == | Equality | $a == $b| True if $a & $b contain |
#——————————— | the same elements |
#–| === | Identity | $a ===$b| True if $a & $b contain |
#——————————— | same elements same types |
#–| != | Inequality| $a != $b| True if $a and $b do not |
#———————————–| contain the same elements|
#–| <> | Inequality| $a<>$b | The same as != |
#–| !== | Non-Identi| $a !==$b| True if $a and $b do not |
#———————————–| contain the same elements|
#———————————–| with same types and order|

PART TWO : Multidimensional Arrays

So far, we have been using one dimensional arrays. What happens when you want to store more than one piece of data about each of our products, then we could use a two-dimensional array! Let us take a look:

#Using Multidimensional arrays to store more data
#Arrays inside an array showcase:
$products = array(array(‘TIR’, ‘Tires’, 100),
array(‘OIL’, ‘Oil’, 10),
array(‘SPK’, ‘Spark Plugs’, 25));
#Think of a multidimensional array as columns and rows.
#The top row is row 0 and far-left column is column 0
#let us access the contents of our multidimensional array

echo ‘|’.$products[0][0].’|’.$products[0][1].’|’.$products[0][2];
echo ‘|’.$products[1][0].’|’.$products[1][1].’|’.$products[1][2];
echo ‘|’.$products[2][0].’|’.$products[2][1].’|’.$products[2][2];

#Alternatively, using a for loop, we can do the same thing:
for($row = 0; $row < 3; $row++){
for($column = 0; $column < 3; $column++){
echo ‘|’.$products[$row][$column];
echo ‘<br />’;

#Using nested for loops seems cleaner and shorter than trying
#to access data using the first means.
#What if you wanted to use column names instead of numbers,
#You could do the following instead.

$products = array(array(‘Code’ => ‘TIR’,
‘Description’ => ‘Tires’,
‘Price’ => 100),
array(‘Code’ => ‘OIL’,
‘Description’ => ‘Oil’,
‘Price’ => 10),
array(‘Code’ => ‘SPK’,
‘Description’ => ‘Spark Plugs’,
‘Price’ => 15)
#Now let us use a for loop to display some data
for($row = 0; $row < 3; $row++){
echo ‘|’.$products[$row][‘Code’].’|’
.$products[$row][‘Price’].’|<br />’;

#Also, you can use a list construct like so:
for($row=0; $row < 3; $row++){
while(list($key, $value) = each($products[$row])){
echo “|$value”;
echo “|<br />”;
#You don’t have to stop at two dimensional arrays! Think of 3?
#Assuming we want to put our products in categories, then using a
#3-dimensional array, we would do this:

$categories = array(array(array(‘CAR_TIR’, ‘Tires’, 100),
array(‘CAR_OIL’, ‘Oil’, 10),
array(‘CAR_SPK’, ‘Spark Plugs’, 20)
array(array(‘VAN_TIR’, ‘Tires’, 150),
array(‘VAN_OIL’, ‘Oil’, 15),
array(‘VAN_SPK’, ‘Spark Plugs’, 40)
array(array(‘TRK_TIR’, ‘Tires’, 300),
array(‘TRK_OIL’, ‘Oil’, 50),
array(‘TRK_SPK’, ‘Spark Plugs’, 60)

#Let us use nested for loops to print the data out!
for ($layer = 0; $layer < 3; $layer++) {
echo “Layer $layer<br />”;
for ($row = 0; $row < 3; $row++) {
for ($column = 0; $column < 3; $column++) {
echo ‘|’.$categories[$layer][$row][$column];
echo ‘|<br />’;


Sorting Arrays
Let us take a look at what sorting means as far as arrays are concerned:

#Using sort()
$products = array(‘Tires’, ‘Oil’, ‘Spark Plugs’);
sort($products) #alphabetically ascending order
$prices = array(100, 45, 300);
sort($prices) #numerical ascending order

#Other Sorting functions
$prices = array( ‘Tires’=>100, ‘Oil’=>10, ‘Spark Plugs’=>4 );
asort($prices); #asort() sorts values rather than keys
ksort($prices) #ksort() sorts keys rather than values

#All the above sorting methods sort in ascending order.
#To do the sorting in reverse, they have corresponding functions


Sorting Multidimensional Arrays
Sorting multidimensional arrays is more complicated than one-dimensional arrays! Let us do something here really quick:

#Using our previous array example:
$products = array( array( ‘TIR’, ‘Tires’, 100 ),
array( ‘OIL’, ‘Oil’, 10 ),
array( ‘SPK’, ‘Spark Plugs’, 4 ) );

#Now we need to write our own comparison function
#then we will pass it to usort()
function compare($x, $y){
if($x[2] == $y[2]){
return 0;
}else if($x[2] < $y[2]){
return -1; #keep an eye on this value
return 1; #look carefully at this

#Now we can sort!
usort($products, ‘compare’);
#after this sorting, our products will be sorted in ascending
#order by price!
#To sort by a different order, you can write another function
#To do a reverse sort, use (rsort(), arsort(), krsort()

function reverse_compare($x, $y){
if($x[2] == $y[2]){
return 0;
}else if($x[2] > $y[2]){
return 1; #Now keep an eye on this. See something?
return -1; #Now look at this. See anything?

usort($products, ‘reverse_compare’); #descending order by price

Reordering Arrays
For some reasons, you might want to manipulate the order of your arrays. You can do this using shuffle() and array_reverse().
Consider our simple shopping cart: assuming we wanted to display random photos of our products for customers to see. All we would have to do is create an array of images and then pass them to shuffle function! Simple!
array_reverseve() function takes an array, creates a new one with the same content in reverse order.

That is good enough for today! Phew! I know, longer than I had thought.
I should mention that although this post has so much details on Arrays, there are a lot more concepts that are available to you through the documentations. There are other functions, like count(), sizeof() and more. I highly recommend trying them out yourself and seeing what exactly is going on! I promise to shorten my next posts! Thank you for stopping by and I hope this was helpful to you. Got questions? Please ask and we can answer them together! See you soon!

Be The First To Get New Posts From Simple Developer…

Written By Elisha Chirchir

Elisha Chirchir is a software developer. He is also the founder of Simple Developer and co-founder of Instinctive Software Solutions. On any given day, he works on both Android and Web Development. During his 'free time', he offers training to those interested in learning how to code in php, java, python, javaScript etc. You can easily find him on StackOverflow Android chatroom or on Twitter @Eenvincible

Leave a Reply

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