PHP Tutorials : Arrays
In this PHP Tutorial you will learn about Array basics, Creating an array, Creating a numeric array and Finding the Size of an Array.
Array basics:
An array is made up of elements. Each element has a key and a value. An array holding information about the GPAs of a student has courses names for keys and GPAs for values:
Course | GPA |
Introduction to computer | A |
Introduction to programming | B+ |
Discrete structure | B |
Computer organization | A- |
An array can only have one element with a given key. In the GPA array, there can’t be another element with the key Discrete structure even if its value is B. However, the same value can appear many times in one array.
Creating an array:
To create an array, assign a value to a particular array key. Array keys are denoted with square brackets.
Example:
// An array called $fruits with string keys
$fruits[‘Apple’] = ‘red’;
$fruits[‘Banana’] = ‘yellow’;
$fruits[‘orange’] = ‘orange’;
You can also create an array using the array( ) language construct.
Example:
$fruits = array(‘Apple’ => ‘red’,
‘Banana’=> ‘yellow’,
‘orange’=> ‘orange’);
With array( ), you specify a comma-delimited list of key/value pairs.
The key and the value are separated by =>.
The square bracket syntax is better when you are adding elements one by one.
Creating a numeric array:
PHP provides some shortcuts for working with arrays that have only numbers as keys.
If you create an array with array( ) by specifying only a list of values instead of key/value pairs, the PHP interpreter automatically assigns a numeric key to each value.
The keys start at 0 and increase by 1 for each element.
Example:
$fruits = array(‘apple’, ‘banana’, ‘orange’);
print “I want an $fruits[0].";
This will print ‘I want an apple.’
PHP automatically uses incrementing numbers for array keys when you create an array or add elements to an array with the empty brackets syntax.
Example:
// This sets $fruits[0]
$fruits[] = ‘apple’;
// This sets $fruits [1]
$fruits[] = ‘banana’;
// Create $fruits with three elements
$fruits = array(‘apple’, ‘banana’, ‘orange’);
// Add an element to the end of $fruits
// This sets $fruits[3]
$fruits[] = ‘pineapple’;
The empty brackets add an element to the array.
The element has a numeric key that’s one more than the biggest numeric key already in the array.
If the array doesn’t exist yet, the empty brackets add an element with a key of 0.
Finding the Size of an Array:
To find the size of an array, use the function count().
count() takes one argument, which is the array, and returns an integer represents the number of the elements of this array.
Example:
$fruits = array(‘apple’, ‘banana’, ‘orange’);
$num = count($fruits);
print “There are $num types of fruits.”;
This will print ‘There are 3 types of fruits’.