Day 6: Array and foreach loop

Array can hold more than one value at a time. It’s a organized collection of key-value pairs. By default keys of array starts with 0, whoever we can define our own keys also.

Syntax:
$Ar = Array(emement1, emement2, emement3,…);

Program 21: Define and display indexed array.

<?php
$ar = Array(30,56,amit,ravi);
for($i=0; $i < count($ar); $i++) {
echo $ar[$i];
echo “<br/>”;
}
?>

OUTPUT:
30
56
amit
ravi
Note: count() function is used to count the length of array.


Program 22: Define and display Associative Array.

<?php
$ar = array(“name”=>”albert”,”age”=>”37″,”address”=>”#54″);
foreach ($ar as $val) {
echo $val;
echo “<br/>”;
}
?>

OUTPUT:
albert
37
#54

Note: we can’t display all the element of associative array with simple for loop because it may or may not contains all the keys/indexes as integer values like above, so foreach loop is used to display all the elements of associative array.

foreach loop will display all the elements of associative array one by one, either key of array is an integer or string.


Program 23: Define and Display Multidimensional Array.

<?php
$students =array (
array(1,”ravi”,50),
array(2,”deepak”,67),
array(3,”sonu”,89)
);
foreach ($students as $val) {
foreach($val as $value) {
echo $value.” “;
}
echo “<br/>”;
}
?>

OUTPUT:
1 ravi 50
2 deepak 67
3 sonu 89



Program 24: print_r() function, is used to return an array in a human readable form.

<?php
$students =array (
array(1,”ravi”,50),
array(2,”deepak”,67),
array(3,”sonu”,89)
);
echo “<pre>”;
print_r($students);
echo “</pre>”;
?>

OUTPUT:
Array
(
[0] => Array
(
[0] => 1
[1] => “ravi”
[2] => 50
)

[1] => Array
(
[0] => 2
[1] => “deepak”
[2] => 67
)

[2] => Array
(
[0] => 3
[1] => “sonu”
[2] => 89
)

)


Some PHP array functions:

  • is_array($ar) – returns true is argument ($array) is array else false.
  • sort($array) – returns sort arrays in ascending order
  • rsort($array) – returns sort arrays in descending order
  • asort($array) – returns sort associative arrays in ascending order, according to the value
  • ksort($array) – returns sort associative arrays in ascending order, according to the key
  • arsort($array) – returns sort associative arrays in descending order, according to the value
  • krsort($array) – returns sort associative arrays in descending order, according to the key

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.