Program:
<?php
$list=array(“Jan”=>1,”Feb”=>2);
echo “month number”;
foreach($list as $month=>$number)
echo”\n”;
echo $month;
echo $number;
?>
Built in Functions of Arrays:
• array(var1,var2,…): Creates a new array which contains all values.
• array-intersect(ar1,ar2,…): Returns a new array which contains all elements form array1 which present in other arrays.
• asort(): sorts associative array functions.
• sort(): Sorts normal array.
• rsort() - sort arrays in descending order.
• ksort() - sort associative arrays in ascending order, according to the key.
• arsort() - sort associative arrays in descending order, according to the value.
• krsort() - sort associative arrays in descending order, according to the key.
• array-reverse(ar): Returns array which contains elements butin reverse order of given array.
• array-pop(ar): Removes the last element from an array and returns it.
• array-push(ar,var1,var2,…): Adds one or more elements to the end of an array.
• array-shift(ar): Returns the first element of an array, which is removed from the array.
• array-unshift(ar,var1,var2,…): Pushes one or more elements into starting of an array.
• array-slice(ar,offset, [length]): Returns a subarray starting at position indicated by the offset parameter.
• is- array(var): Returns true if the variable is array.
• is-array($var,ar)Returns true if the variable is present in array
Example for array built in functions
<?php
$cars = array( "Volvo","BMW", "Toyota”);
sort($cars);
rsort($cars);
$numbers = array( 4, 6,2,22,11);
sort($numbers);
rsort($numbers);
$age = array("Peter" => "35", "Ben" => "37","Joe" => "43");
asort($age);
ksort($age);
arsort($age);
krsort($age);
?>
PHP Functions
A simple function that writes my name when it is called:
<html>
<body>
<?php
function writeName()
{
echo "Ria Zafira";
}
echo "My name is ";
writeName();
?>
</body>
</html>
Function with parameters:
<html>
<body>
<?php
function writeName($fname)
{
echo $fname . " Syed.<br>";
}
echo "My name is ";
writeName("Ayaan");
echo "My sister's name is ";
writeName("Safoora");
echo "My brother's name is ";
writeName("Amaan");
?>
</body>
</html>
Functions with Return values
<html>
<body>
<?php
function add($x, $y)
{
$total = $x + $y;
return $total;
}
echo "1 + 16 = " . add(1, 16);
?>
</body>
</html>