PHP: Create an Array

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:


And the contents of array $companies looks like:

    [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:


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:

    [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.

6 thoughts on “PHP: Create an Array”

  1. Pingback: PHP: Create an Array of A Range of Characters (Numbers or Letters) or Multiple Identical Values

  2. 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.

  3. make an array dt serializes and collects all the elements of d $_POST array. So u can access them by element number

Comments are closed.

Scroll to Top