Posted under » PHP on 26 April 2009
Continued from Array intro. For Python array.
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 array. For array sort in Python.
$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";
}
It appears that $myarray has no key but in the above example, there are always keys assigned to values.
You can assign your own keys by creating an associative array which has $key and $value pairs
$shapes = array('Soda can' => 'Cylinder',
'Notepad' => 'Rectangle',
'Apple' => 'Sphere',
'Orange' => 'Sphere',
'Phonebook' => 'Rectangle');
foreach ($shapes as $key => $value) {
print "The $key is a $value.<br />";
}
To create associative array from query.
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.