PHP Basics Series – Arrays

When working with PHP Arrays are by far the most flexible structure that you can deal with. If we look back to C++ language and looked to the structures for controlling Stack, FIFO, Priority List, etc, we had to define the whole structures to work with.

PHP offer you object construction to help you creating that or Arrays (and SPL – will discuss this later, in the advanced series).

To have an idea how flexible arrays are, they are used from storing retrieved data information from the database to holding session variables.

When talking about arrays you can really write a book about it, but to give a focus on the context and make it simple, I will be showing how the structure works, a simple output function, some sorting functions, the list function and pointing up some functions that you must know.

The array structure is pretty much a system of KEY pointing to VALUE, where the value can be anything scalar (0 => ‘value’) or dynamic (0 => array()) and the key have to be a scalar value restricted to integer and string.

There are a couple of ways to declare an array, but the best and effective way is to declare it blank and then add the values.

$newArray = array();

There is no real performance or reason why you should not add the values on the array while declaring it, but it really does help the code to be cleaner and more readable.

Arrays can hold other arrays inside of it and this can go on and on, so, if you need to declare a multi-dimensional array, just place an array inside another. All the rest is only accessing it’s values.

3 level array

$multi = array();
$multi[] = array();
$multi[0][] = array();
$multi[0][0] = ‘the final value’;

As mentioned before the arrays can have 2 types of keys, integer and strings. These types of keys are precisely the ones that will split the array in 2 categories, common arrays and associative arrays.

The associative arrays are largely used while working with database and form processing. You can easily set the key to be the column name and it’s value the current row value. The common arrays is the default type, so every time you declare an array, unless you declare the key as something different, it will always be an integer. On the common array, unless specified, the array will always start at zero, but you can set it to place the value on a given key.

Just to give some examples, here are the 2 types:

$associativeArray = array();
$associativeArray[‘first_name’] = ‘John’;
$associativeArray[‘last_name’] = ‘Smith’;

// usually while working with database you would dynamically set the array in a for loop

$commonArray = array();
$commonArray[] = ‘John’; // or $commonArray[0] = ‘John’
$commonArray[] = ‘Smith’;

Accessing the array both arrays would be pretty direct. On the associative you would go by:

echo $associativeArray[‘first_name’]; // will display John

and the common array you would use an integer starting at 0:

echo $commonArray[0]; // will display John

Off course the associative array is more meaningful while working with data and it’s also the array type used on the $_SESSION, $_POST, $_GET and $_REQUEST arrays. The session array keeps every single information about the current session (if the session is set and started), the one from PHP and the ones that you are storing, like, for instance, a user login encrypted information or even a shopping cart list.

Consider that you have a shopping cart application and you need to store the cart contents in the session array. The best way to store it is by keeping the array with the shopping cart list inside the session array.

$_SESSION[‘cart_list’] = $arrayOfShoppingCartList; // a pre-existing array with all the current user selected products and it’s quantity.

While programming, some times, gets hard to know what the array is storing, so outputting it is always a good way out to debug. The best way to output an array is by using the print_r function, while echoing will only display “array” as result.

While debugging use:

<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>

It would result:

Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)

Outputting the array contents for the user needs some more attention. You can use the array_walk function and associate a function with it to display the array elements or you can simply add a loop to go trough the array and print it’s content.

To finish up let’s just take a look on a couple of array sorting functions and a great function, list:

  • asort – will sort an array and keep the index association
  • sort – will sort an array, from lower to higher, but reogarnizing the indexes
  • ksort – will sort an array by key

The list function is a great tool to dinamically attach an variable to each element from an array, associative or not.

list(‘fname’, ‘lname’, ‘zip’, ‘country’) = array(‘John’, ‘Smith’, 33065, ‘USA’);

The list function will dinamically create the variables $fname, $lname, $zip and $country with the array values (in sequence). The only thing to be careful about is that list requires that the number of variables created is also the number of values of the array.

list(‘fname’, ‘lname’, ‘zip’, ‘country’) = array(‘John’, ‘Smith’, 33065); // will throw an error

There are 3 functions, not mentioned at this article, that you should take a look at on the PHP documentation:

  • explode and implode, the only 2 php functions which will allow you to convert an string into an array and vice-versa (Zend Exam)
  • is_array is a great tool on if statements that will allow you to easily verify it the value passed is really an array

Check the PHP documentation for all arrays functions. Most of them got examples and get confortable working with arrays. They are the by far the structure that is most used on any PHP script.

http://us2.php.net/manual/en/ref.array.php

On the advanced series, I will be focusing a bit on the SPL structure. It came with PHP 5.3 and will probably be a nice substitute for the array. The benchmarks, so far, are poiting for it being faster, way faster.

On the next article we will be having an overview of the conditional structures of PHP.

Have fun.

Advertisements

About mcloide

Making things simpler, just check: http://www.mcloide.com View all posts by mcloide

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: