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.

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

// To count number of elements stored in array x

echo count($x);

// To populate value from any specific index or position

//echo $x[1];

// output – Hirdesh

// To print all elements in array x – using for-each loop

echo ” <br>Names are :”;

foreach ($x as $val)

{

echo  $val . ” “;

}

echo “<br> using for loop <br>”;

50

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-

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 . ” “;

}

php book webs jyoti
php book webs jyoti

Leave a Comment