Arrays in PHP

Arrays in PHP

An array is a data structure that stores similar type of values in a common variable. Arrays are also called homogeneous data type.

For example if you want to store 50 numbers then instead of defining variables it is easy to define an array with size of 50.

In PHP, the array() function is used to create an array

Arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero.

Example

$x=array(“Laxmi”,”Hirdesh”,”Rahim”,”Ashu”,”Amit”);

From the above diagram, values showing in each boxes called index in array. Insertion of values in array always starts from first index i.e. 0.

To count number of elements stored in array count() method is used in PHP Arrays

echo count($x);

After the array is declared and assigned, you can populate value from any specific index as follow

echo $x[1];    // output – Hirdesh

 

To print all elements present in array x you can use for-each or simply for loop as follow

Using foreach loop

foreach ($x as $val)

{

echo  $val . ” “;

}

Using For loop

for($i=0; $i<count($x); $i++)

{

echo $x[$i] . “<br>”;

}

 

Sorting Arrays: PHP provides many easy ways to sort array values in predefined orders (Ascending and Descending)

arsort: Sorts the array in descending value order and maintains the key/value relationship

asort: Sorts the array in ascending value order and maintains the key/value relationship

rsort: Sorts the array in descending value order

sort: Sorts the array in ascending value order

 

Examples – Sorting of arrays

$x=array(“laxmi”,”hirdesh”,”rahim”,”ashu”,”amit”, “mohit”);

// rsort for DESC and simply sort for ASC

sort($x);

foreach ($x as $val)

{

echo  $val . ” “;

}

Associative Arrays

The associative arrays are similar to default arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can bind them between key and respective values.

asort for displaying in ASC by value (numeric value) the same arsort for DESC

echo “<br> ASort <br>”;

$emp = array(“hirdesh”=>”12”, “Amit”=>”54”, “Laxmi”=>”50”, “Rahim”=>”87”);

asort($emp);

foreach($emp as $x => $code)

{

echo “Name=” . $x . “, Emp Code=” . $code .” <br>”;

}

ksort for displaying in ASC by Key (names or first key string)  the same krsort for DESC

echo “<br> KSort <br>”;

$emp = array(“Hirdesh”=>”12”, “Amit”=>”54”, “Laxmi”=>”50”, “Rahim”=>”87”);

ksort($emp);

foreach($emp as $x => $code)

{

echo “Name=” . $x . “, Emp Code=” . $code .” <br>”;

}