In this Lesson will learn about:
I. Indexed Arrays
II. Sorting Arrays
1
What is an Array?
Array is a special variable, which can hold more than
one value at a time.
Single variables could look like this:
$subject=“Computer";
$subject=“Account";
$subject=“Management";
An array stores multiple values in one single variable:
$subject=array("Computer","Account","Management");
2
Create an Array in PHP
In PHP, the array() function is used to create an array:
array();
Types of arrays:
- Indexed arrays - Arrays with numeric index
- Associative arrays - Arrays with named keys
3
PHP Indexed Arrays
There are two ways to create indexed arrays:
The index can be assigned automatically (index always
starts at 0):
$subject=array("Computer","Account","Management");
or the index can be assigned manually:
$subject[0]=“Computer";
$subject[1]=“Account";
$subject[2]=“Management";
4
PHP Associative Arrays
Associative arrays are arrays that use named keys that you
assign to them.
There are two ways to create an associative array:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
or:
$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";
5
Get The Length of an Array - The count() Function
The count() function is used to return the length (the number of elements) of an array:
Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Loop Through an Indexed Array
To loop through and print all the values of an indexed array, you could use a for loop, like
this:
Example
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
6
Loop Through an Associative Array
To loop through and print all the values of an associative
array, you could use a foreach loop, like this:
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
7
The elements in an array can be sorted in alphabetical or numerical order,
descending or ascending.
PHP - Sort Functions For Arrays
In this chapter, we will go through the following PHP array sort functions:
sort() - sort arrays in ascending order
rsort() - sort arrays in descending order
asort() - sort associative arrays in ascending order, according to the value
arsort()-sort associative arrays in descending order, according to the value
ksort() - sort associative arrays in ascending order, according to the key
krsort() - sort associative arrays in descending order, according to the key
8
Example:
<?php
$subject=array("Computer","Account","Management");
Sort($subject);
Foreach($subject as $sub){
echo “$sub”;
echo “<br/>”;
}
?>
9
Example:
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
ksort($age);
Foreach($age as $X){
echo “$X”;
echo “<br/>”;
}
?>
10
11