PHP Program Tutorial
Please leave a remark at the bottom of each page with your useful suggestion.
Table of Contents
PHP Program Collection 3
- Write a PHP script to calculate and display average temperature, five lowest and highest temperatures.
- Write a PHP function to change the following array's all values to upper or lower case.
- Write a PHP script which displays all the numbers between 200 and 250 that are divisible by 4.
- Write a PHP script to get the shortest/longest string length from an array.
- Write a PHP script to get the largest key in an array.
- Write a PHP function to floor decimal numbers with precision.
- Write a PHP script to sort the following array by the day (page_id) and username.
- Write a PHP program that multiplies corresponding elements of two given lists.
- Write a PHP script to count the total number of times a specific value appears in an array.
- Write a PHP a function to remove a specified duplicate entry from an array.
- Write a PHP script to count the total number of times a specific value appears in an array.
- Write a PHP script to trim all the elements in an array using array_walk function.
- Write a PHP script to delete a specific value from an array using array_filter() function.
- Write a PHP a function to remove a specified duplicate entry from an array.
- Write a PHP program to generate an array with a range taken from a string.
- Write a PHP program to convert word to digit.
- Write a PHP program to check if the bits of the two given positions of a number are same or not.
- Write a PHP program to print out the multiplication table upto 6*6.
- Write a PHP program to print Current date.
- List files in a directory to table.
31. Write a PHP script to calculate and display average temperature, five lowest and highest temperatures.
<?php
$month_temp = "78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 81, 76, 73,
68, 72, 73, 75, 65, 74, 63, 67, 65, 64, 68, 73, 75, 79, 73";
$temp_array = explode(',', $month_temp);
$tot_temp = 0;
$temp_array_length = count($temp_array);
foreach($temp_array as $temp)
{
$tot_temp += $temp;
}
$avg_high_temp = $tot_temp/$temp_array_length;
echo "Average Temperature is : ".$avg_high_temp.";
sort($temp_array);
echo " List of five lowest temperatures :";
for ($i=0; $i< 5; $i++)
{
echo $temp_array[$i].", ";
}
echo "List of five highest temperatures :";
for ($i=($temp_array_length-5); $i< ($temp_array_length); $i++)
{
echo $temp_array[$i].", ";
}
?>
32. Write a PHP function to change the following array's all values to upper or lower case.
<?php
function array_change_value_case($input, $ucase)
{
$case = $ucase;
$narray = array();
if (!is_array($input))
{
return $narray;
}
foreach ($input as $key => $value)
{
if (is_array($value))
{
$narray[$key] = array_change_value_case($value, $case);
continue;
}
$narray[$key] = ($case == CASE_UPPER ? strtoupper($value) : strtolower($value));
}
return $narray;
}
$Color = array('A' => 'Blue', 'B' => 'Green', 'c' => 'Red');
echo 'Actual array ';
print_r($Color);
echo 'Values are in lower case.';
$myColor = array_change_value_case($Color,CASE_LOWER);
print_r($myColor);
echo 'Values are in upper case.';
$myColor = array_change_value_case($Color,CASE_UPPER);
print_r($myColor);
?>
33. Write a PHP script which displays all the numbers between 200 and 250 that are divisible by 4.
<?php
echo implode(",",range(200,250,4))."\n";
?>
34. Write a PHP script to get the shortest/longest string length from an array.
<?php
$my_array = array("abcd","abc","de","hjjj","g","wer");
$new_array = array_map('strlen', $my_array);
// Show maximum and minimum string length using max() function and min() function
echo "The shortest array length is " . min($new_array) .
". The longest array length is " . max($new_array).'.';
?>
35. Write a PHP script to get the largest key in an array.
<?php
$ceu = array( "Italy"=>"Rome"
"Luxembourg"=>"Luxembourg"
"Belgium"=> "Brussels",
"Denmark"=>"Copenhagen"
"Finland"=>"Helsinki"
"France" => "Paris"
"Slovakia"=>"Bratislava",
"Slovenia"=>"Ljubljana"
"Germany" => "Berlin"
"Greece" => "Athens"
"Ireland"=>"Dublin",
"Netherlands"=>"Amsterdam"
"Portugal"=>"Lisbon"
"Spain"=>"Madrid"
"Sweden"=>"Stockholm",
"United Kingdom"=>"London"
"Cyprus"=>"Nicosia"
"Lithuania"=>"Vilnius"
"Czech Republic"=>"Prague"
"Estonia"=>"Tallin"
"Hungary"=>"Budapest"
"Latvia"=>"Riga"
"Malta"=> "Valetta",
"Austria" => "Vienna"
"Poland"=>"Warsaw");
$max_key = max( array_keys( $ceu) );
echo $max_key."\n";
?>
36. Write a PHP function to floor decimal numbers with precision.
<?php
function floorDec($number, $precision, $separator)
{
$number_part=explode($separator, $number);
$number_part[1]=substr_replace($number_part[1],$separator,$precision,0);
if($number_part[0]>=0)
{
$number_part[1]=floor($number_part[1]);}
else
{
$number_part[1]=ceil($number_part[1]);
}
$ceil_number= array($number_part[0],$number_part[1]);
return implode($separator,$ceil_number);
}
print_r(floorDec(1.155, 2, ".")."\n");
print_r(floorDec(100.25781, 4, ".")."\n");
print_r(floorDec(-2.9636, 3, ".")."\n");
?>
37. Write a PHP script to sort the following array by the day (page_id) and username.
<?php
$arra[0]["transaction_id"] = "2025731470";
$arra[1]["transaction_id"] = "2025731450";
$arra[2]["transaction_id"] = "1025731456";
$arra[3]["transaction_id"] = "1025731460";
$arra[0]["user_name"] = "Sana";
$arra[1]["user_name"] = "Illiya";
$arra[2]["user_name"] = "Robin";
$arra[3]["user_name"] = "Samantha";
//convert timestamp to date
function convert_timestamp($timestamp){
$limit=date("U");
$limiting=$timestamp-$limit;
return date ("Ymd", mktime (0,0,$limiting));
}
//comparison function
function cmp ($a, $b) {
$l=convert_timestamp($a["transaction_id"]);
$k=convert_timestamp($b["transaction_id"]);
if($k==$l){
return strcmp($a["user_name"], $b["user_name"]);
}
else{
return strcmp($k, $l);
}
}
//sort array
usort($arra, "cmp");
//print sorted info
while (list ($key, $value) = each ($arra))
{
echo "\$arra[$key]: ";
echo $value["transaction_id"];
echo " user_name: ";
echo $value["user_name"];
echo "\n";
}
?>
38. Write a PHP program that multiplies corresponding elements of two given lists.
<?php
function multiply_two_lists($x, $y)
{
$a = explode(' ',trim($x));
$b = explode(' ',trim($y));
foreach($a as $key=>$value)
{
$output[$key] = $a[$key]*$b[$key];
}
return implode(' ',$output);
}
echo multiply_two_lists(("10 12 3"), ("1 3 3"))."\n";
?>
39. Write a PHP script to count the total number of times a specific value appears in an array.
<?php
function count_array_values($my_array, $match)
{
$count = 0;
foreach ($my_array as $key => $value)
{
if ($value == $match)
{
$count++;
}
}
return $count;
}
$colors = array("c1"=>"Red", "c2"=>"Green", "c3"=>"Yellow", "c4"=>"Red");
echo "\n"."Red color appears ".count_array_values($colors, "Red"). " time(s)."."\n";
?>
40. Write a PHP a function to remove a specified duplicate entry from an array.
<?php
function array_uniq($my_array, $value)
{
$count = 0;
foreach($my_array as $array_key => $array_value)
{
if ( ($count > 0) && ($array_value == $value) )
{
unset($my_array[$array_key]);
}
if ($array_value == $value) $count++;
}
return array_filter($my_array);
}
$numbers = array(4, 5, 6, 7, 4, 7, 8);
print_r(array_uniq($numbers, 7));
?>
41. Write a PHP script to count the total number of times a specific value appears in an array.
<?php
function count_array_values($my_array, $match)
{
$count = 0;
foreach ($my_array as $key => $value)
{
if ($value == $match)
{
$count++;
}
}
return $count;
}
$colors = array("c1"=>"Red", "c2"=>"Green", "c3"=>"Yellow", "c4"=>"Red");
echo "\n"."Red color appears ".count_array_values($colors, "Red"). " time(s)."."\n";
?>
42. Write a PHP script to trim all the elements in an array using array_walk function.
<?php
$colors = array( "Red ", " Green", "Black ", " White ");
print_r($colors);
array_walk($colors, create_function('&$val', '$val = trim($val);'));
print_r($colors);
?>
43. Write a PHP script to delete a specific value from an array using array_filter() function.
<?php
$colors = array('key1' => 'Red', 'key2' => 'Green', 'key3' => 'Black');
$given_value = 'Black';
print_r($colors);
$new_filtered_array = array_filter($colors, function ($element) use ($given_value)
{
return ($element != $given_value);
}
print_r($filtered_array);
print_r($new_filtered_array);
?>
44. Write a PHP a function to remove a specified duplicate entry from an array.
<?php
function array_uniq($my_array, $value)
{
$count = 0;
foreach($my_array as $array_key => $array_value)
{
if ( ($count > 0) && ($array_value == $value) )
{
unset($my_array[$array_key]);
}
if ($array_value == $value) $count++;
}
return array_filter($my_array);
}
$numbers = array(4, 5, 6, 7, 4, 7, 8);
print_r(array_uniq($numbers, 7));
?>
45. Write a PHP program to generate an array with a range taken from a string.
<?php
function string_range($str1)
{
preg_match_all("/([0-9]{1,2})-?([0-9]{0,2}) ?,?;?/", $str1, $a);
$x = array ();
foreach ($a[1] as $k => $v)
{
$x = array_merge ($x, range ($v, (empty($a[2][$k])?$v:$a[2][$k])));
}
return ($x);
}
$test_string = '1-2 18-20 9-11';
print_r(string_range($test_string));
?>
46. Write a PHP program to convert word to digit.
<?php
function word_digit($word) {
$warr = explode(';',$word);
$result = '';
foreach($warr as $value){
switch(trim($value)){
case 'zero':
$result .= '0';
break;
case 'one':
$result .= '1';
break;
case 'two':
$result .= '2';
break;
case 'three':
$result .= '3';
break;
case 'four':
$result .= '4';
break;
case 'five':
$result .= '5';
break;
case 'six':
$result .= '6';
break;
case 'seven':
$result .= '7';
break;
case 'eight':
$result .= '8';
break;
case 'nine':
$result .= '9';
break;
}
}
return $result;
}
echo word_digit("zero;three;five;six;eight;one")."\n";
echo word_digit("seven;zero;one")."\n";
?>
47. Write a PHP program to check if the bits of the two given positions of a number are same or not.
<?php
function test_bit_position($num, $pos1, $pos2) {
$pos1--;
$pos2--;
$bin_num = strrev(decbin($num));
if ($bin_num[$pos1] == $bin_num[$pos2]) {
return "true";
} else {
return "false";
}
}
echo test_bit_position(112,5,6)."\n";
?>
48. Write a PHP program to print out the multiplication table upto 6*6.
<?php
for ($i = 1; $i < 7; $i++) {
for ($j = 1; $j < 7; $j++) {
if ($j == 1) {
echo str_pad($i*$j, 2, " ", STR_PAD_LEFT);
} else {
echo str_pad($i*$j, 4, " ", STR_PAD_LEFT);
}
}
echo "\n";
}
?>
49. Write a PHP program to print Current date.
<?php
date_default_timezone_set('Asia/Kolkata');
$currentTime = date( 'd-m-Y h:i:s A', time () );
echo $currentTime;
?>
Note: MM When we using XAMPP or WAMP, servername = localhost, username = root, password is empty.
50. List files in a directory to table.
<?php{
$files = glob("files/*.xml");
$files = str_replace("","",$files);
$files = str_replace("files/","",$files);
echo "<table>";
foreach ($files as $filename) {
echo "<tr><td><a href='$filename'>$filename</a></td></tr>";
}
echo "</table>";
}
?>