Displaying Arrays

Posted under » PHP on 26 April 2009

Continued from Array intro.

Looping in array, count and add comma.

The foreach statement is used to loop through arrays.

<¿php
$arr=array("one", "two", "three");

foreach ($arr as $value)
{
  echo "Value: " . $value . "
"; } ?>

You can sort the arrays

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) { 
    echo "fruits[" . $key . "] = " . $val . "\n";
}

You can sort in descending order by rsort($fruits)

You can display only unique items

$myarray = array("lemon", "orange", "banana", "apple");
$fruits = array_unique($myarray);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

Every associative array has $key and $value pairs

<¿php
$shapes = array('Soda can' => 'Cylinder',
'Notepad' => 'Rectangle',
'Apple' => 'Sphere',
'Orange' => 'Sphere',
'Phonebook' => 'Rectangle');
foreach ($shapes as $key => $value) { 
print "The $key is a $value.
"; } ?>

The sort() function sorts an array. The foreach loop selects each element from the array and assigns its value to $key before executing the code in the block.

<¿php
$shapes = array("rectangle", "cylinder", "sphere");
sort($shapes);

foreach ($shapes as $key => $val) {
echo "shapes[" . $key . "] = " . $val . "
"; } ?> Output: shapes[0] = cylinder shapes[1] = rectangle shapes[2] = sphere

Applications : String replacer using XML array | Decoding JSON.

web security linux ubuntu GIT svn Raspberry apache mysql php drupal cake symfony javascript Ajax css