Absolute Beginners Guide to PHP Arrays

Arrays are wonderful ways to organize and use data in PHP.

Quite simply, an array is a list.

Here’s a quick example of an array of types of transportation:

{codecitation}$transportation = array( ‘Planes’, ‘Trains’, ‘Automobiles’ );{/codecitation}

For readability you can write it like this as well:

{codecitation}$transportation = array(

    ‘Planes’,

    ‘Trains’,

    ‘Automobiles’

);{/codecitation}

Now $transportation holds a nice little list of types of transportation. But what do we do with it?

Printing Array Items

Each of the visible items in the list above is called a value. Each value also has a key. If you don’t give an item a key, PHP will assign one, and it’ll be a number. Here’s a better visualization of what’s going on:

{codecitation}$transportation = array(

    0 => ‘Planes’,

    1 => ‘Trains’,

    2 => ‘Automobiles’

);{/codecitation}

The => are assignment operators, and the numbers are the keys. Note that we started with 0. If you’re really assigning them yourself, you can start with 1, but I don’t recommend it, since the automatic system starts with 0.

To print the first element in the array you would do something like this:

{codecitation}<?php echo $transportation[0]; ?>{/codecitation}

See the key there in the square brackets?  This code would output “Planes”.

Custom Array Keys

You can also make up your own keys if you wish to. Here’s an example:

{codecitation}$web_site = array(

    ‘Name’ => ‘OSTraining’,

    ‘URL’ => ‘https://ostraining.com’,

    ‘Purpose’ => ‘Education’

);{/codecitation}

And now you could do something like this:

{codecitation}<ul>

<li>Name: <?php echo $web_site[‘Name’]; ?></li>

<li>URL: <?php echo $web_site[‘URL’]; ?></li>

<li>Purpose: <?php echo $web_site[‘Purpose’]; ?></li>

</ul>{/codecitation}

And you’ll end up with something like this:

Using custom keys can make it much easier to know what it is you’re printing simply by looking at it.

Loops

What if you don’t know how many items are in the array, or what the keys are?  PHP has a wonderful process called foreach. Using the $web_site array from above, here’s how it works:

{codecitation}<ul>

<?php

    foreach( $web_site as $key => $value ) {

        echo ‘<li>’ . $key . ‘:’. $value . ‘</li>’;

    }

?>

</ul>

{/codecitation}

Here’s what that’s doing in plain English:

For each item in the array, assign the variable $key for the key of each item, and $value for the value of each item. Then go through every one of them and print them out, stopping when we don’t have any more.

This code would produce the exact same bulleted list as the one I manually made above.

Foreach makes it very easy to take every array item and do something with it.

Multidimensional Arrays

A multidimensional array is one where the items in an array are themselves arrays. Here’s an example:

{codecitation}

$staff = array(

    0 => array(

        [‘Name’] => ‘Topher’,

        [‘Position’] => ‘Standing or sitting, when not lying down’

    ),

    1 => array(

        [‘Name’] => ‘Steve’,

        [‘Position’] => ‘Writer’

    )

);

{/codecitation}

There we have a $staff array with multiple people in it. We could do multiple foreach functions to iterate over each of those people like this:

{codecitation}foreach( $staff as $key => $person ) {

    echo ‘<ul>’;

        foreach( $person as $attribute => $value ) {

            echo ‘<li>’ . $attribute . ‘:’ . $value . ‘</li>’;

        }

    echo ‘</ul>’;

}

{/codecitation}

In the above example I looped through each person, and within each person I looped through their attributes and printed them. You can make up whatever variable names you wish, there’s nothing magic about the names. I tried to name mine in a way that made sense according to the contents.

Putting It All Together

Arrays holding actual content are rarely handmade like the ones I’ve made in this post. Typically they come to you from a request of something, whether it be a database call, a REST request from a web API or whatever.

In the case of WordPress it’s very common to do a database call with WP_Query and get back a multidimensional array of Blog Post data. At that point you can use foreach to loop through those posts and print them.

The same will hold true of just about any CMS. If you’re making anything custom at all you’re probably making a database call and getting an array of data back.

Going Beyond

There’s much much more that can be done with arrays, far more than can fit into one post. They can be sorted, spliced, compared, counted, and twisted in all sorts of ways. I strongly recommend you read the documentation on the PHP web site. Most of the array functions are logically named, so you can tell what they do by the name. Once you get used to most of them you can do just about anything with arrays.

Bonus Functions

Here are some examples of some easy useful things you can do with arrays:

{codecitation}<?php $items_num = count( $array ); ?>{/codecitation}

Assuming $array actually is an array, it’ll count how many items are in it, so you can do things like “14 search items found” (link)

{codecitation}<?php $array = sort( $array ); ?>{/codecitation}

This will take an array, sort it from low to high, and assign it back to the same variable name. There are options to sort it numerically, or by string, or whatever (link)

{codecitation}<?php if( is_array( $array ) ) {{/codecitation}

This tests to see if your variable is an array or not (link). It can be useful to cast a variable as something else early in your code, like this:

{codecitation}$array = ‘’;{/codecitation}

And then change it to an array when the time is right. With this process you can know whether you’ve gotten your content yet or not.

Wrapping Up

As you can see, arrays can be incredibly flexible and powerful. They’re a wonderful tool for organizing and managing data, and allowing you to use that data in just about any way you can think of.

Author

  • Topher DeRosia

    Topher is an accomplished programmer, having written his own content management systems and managed some very large websites. He loves to help people and believes playing with WordPress is fun. Topher lives in Michigan, USA.

0 0 votes
Article Rating
Subscribe
Notify of
10 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Pedram
Pedram
8 years ago

As an experienced PHP developer, I really enjoyed reading your blog post regarding the PHP Array.

I will definitely reference to it if I ever need to explain arrays to someone.
Many thanks, and keep up the good work!

val_grassroots
val_grassroots
8 years ago

i tested the multidimensional arrays sample codes. i got an error saying “Illegal offset type in”…..

val_grassroots
val_grassroots
8 years ago
Reply to  val_grassroots

i solved it by deleting the square bracket of each key..

John Mark
John Mark
8 years ago

You are telling about arrays in the PHP through this blog you are providing most important information for PHP learners. In this blog you are defining arrays step by step and programming concept. I still run [url=http://www.sagacademy.com/php-development-training-institute]Best PHP development institute in Jaipur[/url] so I know about arrays used in PHP. Really you are doing work well, so please keep updates more information and increase our knowledge.

atif
atif
8 years ago

Nice Post. A very Well written tutorial. You have discussed PHP arrays tutorial, I felt one thing is missing that is PHP array sorting functions. For your reference to continue the tutorial series,I will suggest you to search for PHP array sorting functions at Cloudways

This tutorial series is helping me alot in learning PHP from scratch.

atif
atif
8 years ago

A very well written article. It really added few points to my existing knowledge.

phpassignmenthelp
phpassignmenthelp
7 years ago

The post is written in very a good manner and it entails many useful information for me. I appreciated what you have done here. I am always searching for informative information like this. Thanks for sharing with us.

[url=http://www.phpassignmenthelp.com]http://www.phpassignmenthel…[/url]

pradeepa tamilvanan
pradeepa tamilvanan
7 years ago

What good series of tutorials, thank you very much. These articles are very useful to me .I will implement some for me.[url=http://www.BESTPHPTRAINING.IN/]Best PHP Training in Chennai[/url]

pradeepa tamilvanan
pradeepa tamilvanan
7 years ago

Profiling allows developers to capture information about the performance of a web page or web application. With this information developers can improve the performance of their scripts…click link..[url=http://www.BESTPHPTRAINING.IN/]Best PHP Training in Chennai[/url]

pradeepa tamilvanan
pradeepa tamilvanan
7 years ago

This convention also has the benefit that posts can easily be sorted by publication date. When displayed on your blog, this post will have an URL like click here:

[url=http://www.BESTPHPTRAINING.IN/]PHP Training with Placement in Chennai[/url]
[url=http://www.BESTPHPTRAINING.IN/]PHP Training Classes in Chennai[/url]

10
0
Would love your thoughts, please comment.x
()
x