Welcome to The PHP Blog!
  Welcome to The PHP Blog on the 29th of July!
RSS 2.0
Read the Feed
The PHP Blog
more-advanced-arrays
Dan
January 14, 2009
Basics

More Advanced Arrays

This post is a part two of the first post on the basics of arrays. Today we’ll look at some useful functions built for using with arrays that come as standard with PHP and some more advanced techniques.

Quick Recap

Ok so hopefully you read this tutorial first so that you have a basic understanding of the different types of array and what we can store in them.

Built-in Array Functions

Rather than mess around coding our own functions, which so many new developers do without even looking to see if it’s already been done, PHP comes with quite a lot of built-in functions to do different things with arrays. We’re not going to look at them, just the most useful ones, but if you want to see the complete list then click here.

Basic Functions

The most basic function to do with arrays is simply array() itself which simply creates a new array, PHP is a forgiving language and therefore we don’t need actually need to declare an array, but if adhering to good practice then we use this function like this;

<?php

$my_new_array = array();

?>

This function can also be used to create a standard number-indexed array or an associative array using some parameters, here’s another example;

<?php

// example one - number index (0-4)
$my_pets = array('dog', 'cat', 'frog', 'fish', 'lizard');
echo $my_pets[0]; // will print 'dog' without the quotes

// example two - associative
$fruits = array('banana'=>'yellow', 'pear'=>'green', 'kiwi'=>'green');
echo $fruits['kiwi']; // will print 'green' without the quotes
?>

It’s simple to create arrays with many values on one line using the array() function and can come in handy at times. There are other ways for building arrays though, for example it’s possible to build a multi-dimensional array out of two standard arrays using array_combine(). We all know that a multi-dimensional array needs two things; a key and a value, so all we need is two arrays - one for keys and one for values;

<?php

$key_array = array('the', 'php', blog');
$value_array = array('guitar', 'spork', 'raptor');

$new_array = array_combine($key_array, $value_array);
echo $new_array['blog']; // will print 'raptor' without the quotes

?>

As we can see, ‘the’, ‘php’ and ‘blog’ have become keys whilst ‘guitar’, ’spork’ and ‘raptor’ (the first three things I saw looking around my room (don’t ask).

For Debugging

A great function for when you’re debugging your web application, blog or whatever in between is print_r(). If we use print($some_array) then all we’ll get is PHP printing the word ‘Array’ or similar. If we use print_r($some_array) then we get something a bit more interesting and useful for when we just can’t figure out what’s wrong with our code but we suspect it’s an array, it looks like this;

<?php

$my_array = array('knife', 'fork', 'spoon');
print_r($my_array);

?>

This code will give us an output that looks like this;

Array
(
	[0] => knife
	[1] => fork
	[2] => spoon
)

Now we can see the entire contents of our array, this works for any type of array.

Our next useful function we’re going to look at is array_key_exists(). If you haven’t already guessed what it does, it searches through a multi-dimensional array to see if a key exists, like this;

<?php

$fruits = array('banana'=>'yellow', 'pear'=>'green', 'kiwi'=>'green');

if ( array_key_exists('kiwi', $fruits) )
{
	echo 'Found a kiwi';
}

?>

The above code would print ‘Found a kiwi’ because there is a key called ‘kiwi’ in the array $fruits.

Next we have a function with use in some situations, maybe a random quote generator, or maybe an employer deciding who to fire today; array_rand(). There is no example for this function, it takes two parameters, the first one specifies the array, the second is optional and specifies how many random elements to return (default 1).

For searching through an array, we have the appropriately named array_search(), this function will search an array (second parameter) and if a value exists that matches the search then it’ll return the key. The parameters are; search value, array to search, strict. They are all self explanatory apart from strict, strict is false by default but if changed to true it will be a literal serach, meaning that ‘5′ as a string and the number 5 without quotes are different things. This function is a bit more tricky, here’s an example (without strict);

<?php

$fruits = array('banana'=>'yellow', 'pear'=>'green', 'kiwi'=>'green');
echo array_search('yellow', $fruits); // will print 'banana' without the quotes

?>

Similar to array_search() is a, for some reason more popular, function called in_array(). This function is simplistic, the first parameter is what we’re searching for and the second parameter is the array we’re searching, this function returns true or false.

Nested Arrays

Now we’re wrapping up the useful functions and we’re going to briefly look at something equally useful, nested arrays. Previously we’ve looked at single-dimensional arrays, multi-dimensional arrays and now we’re going to look at nested, nested arrays are basically a multi-dimensional array where some of the values are arrays themselves. Incase you’re confused by how many times I’ve said ‘dimensional’, here’s an example;

<?php

$nested = array('a' => 'the', 'b' => 'php', c => array('1', '2', '3'));
print_r($nested);

?>

Would give us an output a little like this;

Array
(
    [a] => the
    [b] => php
    [c] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

)

As you can imagine, nested arrays can be very useful especially for storing stuff like user data, geographic information or anything in between.

Conclusion

We’ve had a quite a long tutorial with some useful functions, or maybe it just feels like that because it takes longer to write than to read. But we’ve touched on some more advanced techniques we can use with arrays, if you’re interested in reading even more into this subject then click here for a complete list!

Hope you enjoyed this tutorial, if you have any comments or questions then leave a comment.


Sponsored By

Comments


  1. tutorialand
    08:50 On January 17th, 2009

    Nice tutorial, added to http://www.tutorialand.com

  2. Angelo R.
    18:49 On January 17th, 2009

    Just a quick clarification… your first example of a multi-dimensional array is actually an array where you specified the keys. A multi-dimensional array would be more akin to your “nested” array explanation.

  3. Dan
    18:59 On January 17th, 2009

    Hey Angelo, whoops, sorry about that! Fixed now, thanks for noticing =]

  4. Angelo R.
    22:42 On January 17th, 2009

    Not a problem, good introduction to arrays though! Although, I highly recommend beginners try and work out their own functions for some of these (such as, array key exists) and the like. It definitely helps build your programming chops.

  5. J
    22:16 On January 31st, 2009

    Handy for form validation. Thanks!

Post Your Comments







The PHP Blog loves gravatars, get yours today!