07 - Working with Arrays in PHP

Arrays are collection of related values; these values are of similar data types in programming languages for eg: names of students, list of products, list of marks of students etc. Array is a container that is used to store multiple values. These values are stored in memory in contiguous memory locations. Array holds values in key-value pair combination.

In PHP array can be following types:

1. Single dimensional array

Consider the following array:

MondayTuesdayWednesdayThursdayFridaySaturdaySunday
Array Named Days

In the above array named days, we can see 7 elements are stored. We can represent these all values in the following way:

Days[0]=”Monday”
Days[1]=”Tuesday”
Days[2]=”Wednesday”
Days[3]=”Thursday”
Days[4]=”Friday”
Days[5]=”Saturday”
Days[6]=”Sunday”

In square brackets the index of array is displayed, that is the subscript or key of array is considered. In single dimensional array we need only one index to hold any value in given array.

In the following code we have used array to find out the product of first 5 natural numbers:

<?php
$myArray=Array(1,2,3,4,5);
$product=1;
foreach($myArray as $i)
{
    $product*=$i;  
}
echo $product;
?>

2. Multi dimensional array

In multi dimensional array, we use two indices to represent any value. One value is used for row and other for column representation. Multi dimensional array can be represented as:

141178514
736920618
738516152

These values can be represented as follows:

$matrix[0][0]=141;
$matrix[0][1]=178;
$matrix[0][2]=514;
$matrix[1][0]=736;
$matrix[1][1]=920;
$matrix[1][2]=618;
$matrix[2][0]=738;
$matrix[2][0]=516;
$matrix[2][2]=152;
Example:  
 FirstNameLastNameAge
HusbandAdamSmith47
WifeJennySmith39
KidRobinSmith12

This array can be represented in PHP as:

 

$husband=array('firstname'=>'Adam',
'lastname'=>'Smith',
'age=>'47');

This representation is same as:

 
$husband[‘firstname’]=’Adam’;
$husband[‘lastname’]=’Smith’;
$husband[‘age’]=’47’;

If we want to put complete information of above table in one array, it will be multi dimensional array that is array within array.

<?php
$family=array('husband'=>array('Adam','Smith',47),
        'wife'=>array('Jenny','Smith',39),
        'kid'=>array('robin','Smith',12));
echo "Husband: ".$family['husband'][0];
echo " ";
echo $family['husband'][1];
echo "<br>";
echo "Wife: ".$family['wife'][0];
echo " ";
echo $family['wife'][1];
echo "<br>";
echo "Kid: ".$family['kid'][0];
echo " ";
echo $family['kid'][1];
?>

The output of above code will be:

3. Associative array

In PHP, it is not mandatory that we always use index values starting from 0 (zero). We can use any key or index we want to assign for each value of array. This type of array is known as associative array.

For eg:

       $prices=array(“Mouse”=>1500, “Monitor”=>5000,”Printer”=>4500);

This declaration is same as:

$prices[“mouse”]=1500;
$prices[“monitor”]=5000;
$prices[“printer”]=4500;

In associative arrays index is not simply numerical value, that’s why we can’t use simple counter in for loop to deal with these types of array.

For this we can use each() or list() functions in loop as:

<?php
$prices=array("Mouse"=>1500,"Monitor"=>5000,"Printer"=>4500);
while($element=each($prices))
{
    echo $element["key"];
    echo "-";
    echo $element["value"];
    echo "<br>";
}
?>

The output of above code will be as:

  • function returns the current element in array and makes the next element current one. When we use it in while loop, it returns every element in the array in turn and stops when the end of array is encountered.

Sorting array:

Sorting is the process which is used to arrange the elements of an array either in ascending order or in descending order. We can sort an array using sort() function.

<?php
$products=array("mouse","printer","monitor","speaker","hard drive");
echo "array before sorting:";
echo "<br>";
while($element=each($products))
{
    echo $element["value"];
    echo "<br>";
}
echo "<br>";
echo "<br>";
echo "array after sorting:";
echo "<br>";
sort($products);
while($element=each($products))
{
    echo $element["value"];
    echo "<br>";
}
?>

 

The output of above code is as:

If we have to sort an associative array, we cannot use the same sort(), because the keys are strings not numeric values. We need to sort elements to keep keys and values together.

For example:

In the following code we have used asort() function to sort associative array. asort() function sort the array according to values of each element of associative array.

<?php
$prices=array("Mouse"=>1500,"Monitor"=>5000,"Printer"=>4500);
echo "array before sorting";
echo "<br>";
while($element=each($prices))
{
    echo $element["key"];
    echo "-";
    echo $element["value"];
    echo "<br>";
}
echo "<br>";
echo "array before sorting";
echo "<br>";
asort($prices);
while($element=each($prices))
{
    echo $element["key"];
    echo "-";
    echo $element["value"];
    echo "<br>";
}
?>

The output of above code is:

We can use ksort() function, if we want to sort values on the basis of keys, like as:

<?php
$prices=array("Mouse"=>1500,"Monitor"=>5000,"Printer"=>4500);
echo "array before sorting";
echo "<br>";
while($element=each($prices))
{
    echo $element["key"];
    echo "-";
    echo $element["value"];
    echo "<br>";
}
echo "<br>";
echo "array before sorting";
echo "<br>";
ksort($prices);
while($element=each($prices))
{
    echo $element["key"];
    echo "-";
    echo $element["value"];
    echo "<br>";
}
?>

The output of above code is as:

Sorting in reverse manner:

We have used till now sort(), asort() and ksort(), which are used to arrange values in ascending order, we can rsort, arsort and krsort() for the same, like:

<?php
$prices=array("Mouse"=>1500,"Monitor"=>5000,"Printer"=>4500);
echo "array before sorting";
echo "<br>";
while($element=each($prices))
{
    echo $element["key"];
    echo "-";
    echo $element["value"];
    echo "<br>";
}
echo "<br>";
echo "array before sorting";
echo "<br>";
krsort($prices);
while($element=each($prices))
{
    echo $element["key"];
    echo "-";
    echo $element["value"];
    echo "<br>";
}
?>

The output of above code is as:

Working with shuffle()

Sometimes we need to display randomly images or strings on our website. This task can be accomplished using shuffle() function in php as follows:

<?php
$products=array("Mouse","Monitor","Printer","Scanner","Hard drive","Light pen","Speaker","Webcam","Blue ray disc","DVD");
shuffle($products);
?>
<html>
<head>
    <title>Products details</title>
</head>
<body>
<center>
    <h1>Product's Details</h1>
    <table width=100%>
    <tr>
    <?php
    for($i=0;$i<3;$i++)
    {
        echo "<td align=center><h3>$products[$i]</td>";
    }
    ?>
    </tr>
    </table>
    </center>
</body>
</html>

Various outputs of above code is as:

Shuffle() randomly display the product’s details on web page.

Working with array_reverse()

This function takes an array and creates a new one with the same contents in reverse order.

<?php
$numbers=range(1,10);
echo "array before reverse";
echo "<br>";
for($i=9;$i>=0;$i--)
{
    echo $numbers[$i];
    echo "<br>";
}
echo "array after reverse";
echo "<br>";
$numbers=array_reverse($numbers);
for($i=9;$i>=0;$i--)
{
    echo $numbers[$i];
    echo "<br>";
}

The output of above code is:

Working with array_walk()

This function is used when we want to work with each element of array using the same function. That means we want to execute the same function for every element of array.

The syntax of this function is:

       array_walk(array_reference , function_name);

for eg:

if we have to calculate square of first 5 natural numbers, which are stored in an array we can write following script:

<?php
function square($value)
{
    echo $value*$value;
    echo "<br>";
}
$numbers=array(1,2,3,4,5);
array_walk($numbers,"square");
?>

Here we have defined a function square for calculating the square of every element of array:

       The output of the above code is:

Working with array_count_values()

This function is used to count each unique value and its occurrences in an array. This function returns an associative array containing a frequency table, which contains all the unique values from array as keys. Each key has some numeric value that shows how many times the key occurs in array.

<?php
$numbers=array(1,2,3,4,5,1,2,3,4,5,6,4,3,2,5,6,4,3,2,3,4,5,6);
$countarray=array_count_values($numbers);
echo "Key &nbsp;&nbsp;&nbsp;value";
echo "<br>";
while($element=each($countarray))
{
    echo $element["key"];
    echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
    echo $element["value"];
    echo "<br>";
}
?>

The output of above code is:

 

Like us on Facebook