PHP: Create an Array

by Yang Yang on June 2, 2009

Share This Article:
Subscribe to Kavoir: blog feed

Array is probably the simplest compound data type every language supports. It’s basically a set of ordered values (text strings, numbers or booleans and even a child array). You can create an array in PHP by:

$companies = array('Microsoft', 'Google', 'IBM', 'Apple');

Now array $companies contains 4 text string values. You can append one more by:

$companies[] = 'Dell';

Or append yet another element that’s itself an array:

$companies[] = array('Wikipedia', 'Skype');

You can use PHP function print_r() to display the contents of an array:

print_r($companies);

And the contents of array $companies looks like:

Array
(
    [0] => Microsoft
    [1] => Google
    [2] => IBM
    [3] => Apple
    [4] => Dell
    [5] => Array
        (
            [0] => Wikipedia
            [1] => Skype
        )

)

Very intuitive. It’s basically a structured storage of a number (maybe a large number) of atomic values.

Also note that each and every of the values are marked with a unique index across the set which can be used to identify the element for change or retrieval. For example, to get the 4th company whose index is 3, you can do this:

echo $companies[3];

And the PHP would print out:

Apple

Another approach for creating PHP arrays is to create one element a time. For instance, you will generate a series of values and then assign each of them to an additional element in the array:

$numbers = array(); // creating an empty PHP array
for ($i = 1; $i <= 100; $i++) {
	$numbers[] = $i;
}

As you may have got it, the array $numbers now contains all the integers from 1 to 100:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    ...
    [99] => 100
)

You can use array_fill() to form an array with the same values and range() to fill an array with a series of consecutive values.

Share This Article:
Subscribe to Kavoir: blog feed

You should also read:

{ 4 comments… read them below or add one }

ERiK April 15, 2010 at 9:02 am

this doesn’t work in ie 8.0.6. how can i get it to work?? works in ff 3.5.30

Reply

Yang Yang April 26, 2010 at 3:12 pm

I’m sorry if your IE is not in charge of parsing and executing PHP code.

Reply

Kayle April 26, 2010 at 8:54 am

1- Write a PHP program that goes through all integers between 1 and 100 (excluding 1 and 0) and displays each even number on a separate line.
2- Re-write the program in question 1 but this time use a function to go through the
numbers and display them.
3- Write a PHP program that assigns 5 numbers to an array. It should then go through the values in the array to find and display the minimum value in the array.

Reply

Yang Yang April 26, 2010 at 3:11 pm

Again?

Reply

Leave a Comment

{ 1 trackback }

Previous post:

Next post: