Skip to main content

Posts

Showing posts from November, 2019

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':    

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)); ?> @php_program

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)); ?>

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); ?>

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";  ?>

PHP 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)); ?>

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"; ?>

Sort An Array By Day, User Same Or Page Id

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["

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"); ?>

PHP program 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&q

PHP fiction to change array values to upper and 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); ?>

Temperature Calculator using PHP

This is 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].", "; } ?>

Create a contact form using php

Create this file ⬇ contactform.php <html> <head> </head> <body> <h4>Contact Form</h4> <form method="post "action="sendmail .php">  Name : <input type="text"name="uname"><br> Mobile No. : <input type="text" name="mobile"><br> Email id : <input type="text" name="email"><br> Message : <textarea name="message"> </textarea><br> <input type="submit" value="Submit"> </form> </body> </html> sendmail.php <?php $uname = $_POST['uname']; $mobile = $_POST['mobile']; $email = $_POST['email']; $message = $_POST['message']; $to = "phpkish@gmail.com"; $subject = "Contact"; $message = $message."\n Name: ".$uname."\n Mobile: ".$mobile."\n Email: $email; if(mail($to,$s

Read an image from database using PHP

PHP program to Read image from Database.  <?php header("content-type:image/jpeg");     mysql_connect("servername","username","password"); mysql_select_db("databasename");  $sql = "select * from tablename"; $data = mysql_query($sql);     while($rec=mysql_fetch_row($data))    {      echo "$rec[1]<br>";    }  ?>  ------------------------------------------------------------- Note: When we using XAMPP or WAMP, servername = localhost, username = root, password is empty.

Save image to database using PhP

 <?php   if(isset($_POST['sub']))   {   $cont =   file_get_contents($_FILES['f1']['tmp_name']);  $type = $_FILES['f1']['type'];         $cont=addslashes($cont);      mysql_connect("servername","username","password"); mysql_select_db("dbname");   $sql="insert into tablename values ('','$cont','$type')";  if(mysql_query($sql))  echo "Inserted";  else  echo mysql_error();  } ?>  <form method="post" action="" enctype="multipart/form-data">  <input type="file" name="f1"> Image : <input type="submit" value="Upload" name="sub"> </form> -------------------------------------------------------------------- Note: When we using XAMPP or WAMP, servername = localhost, username = root, password is empty.

Fetch data from database using PHP

PHP program to fetch records from the table in Database. <?php $conn = mysqli_connect('servername','username','password','databasename'); if(!$conn) {  die('Connection failed!'.mysqli_error($conn)); } $sql = "SELECT * FROM tablename";   $data = mysqli_query($conn,$sql);   while($rec = mysqli_fetch_row($data)) { echo "$rec[0]<br>"; echo "$rec[1]<br>"; echo "$rec[2]<br>"; } ?>  ------------------------------------------------------------- Note: When we are using XAMPP or WAMP, servername = localhost, username = root, password is empty.

Insert records to database using PHP

Today i am going to write a program to Insert records into the table in Database. <?php  $conn =mysqli_connect('servername','username','password','databasename');  if(!$conn) {  die('Connection failed!'.mysqli_error($conn));  } $sql = "INSERT INTO tablename('sno','name','pwd') VALUES('101','Richy','Richy123')";    if(mysqli_query($conn,$sql)) {  echo "Record Inserted";  } else {  echo mysql_error(); } ?> ------------------------------------------------------------- Note: When we using XAMPP or WAMP, servername = localhost, username = root, password is empty.

Connect to server and select database using php

<?php if(!mysql_connect('servername','username','password'))  {      die('Connection failed!'.mysql_error());  }       if(!mysql_select_db("dbname"))  {  die('Database unavailable'.mysql_error());  }  ?> ------------------------------------------------------------- Note: When we are using XAMPP or WAMP, servername = localhost, username = root, password is empty

Create a database with PHP and Mysql

<?php  if(! mysql_connect('servername','username','password'))  {     die('Connection failed!'.mysql_error());  } $sql = "create database newdb"; if(mysql_query($sql)) {  echo "Database created"; } else {   echo mysql_error(); } ?> ------------------------------------------------------------- Note: When we are using XAMPP or WAMP, servername = localhost, username = root, password is empty.

PHP file upload

Program to Upload a file to the Server. ✡️ form1.php  <html>  <head>  </head>  <body> <form method="post"   action="upload.php" enctype="multipart/     form-data">  Resume : <input type="file" name="f1"> <br> <input type="submit" value="Upload"> </form> </body> </html> ✡️ Upload.php <?php if(is_uploaded_file($_FILES['f1']['tmp_name'])) {  $fname = $_FILES['f1']['name'];            if(move_uploaded_file($_FILES['f1']['tmp_name'],"uploads/$fname"))  {  echo "Uploaded successfully";  } else  {  echo "Not uploaded";  }  } ?>

PHP Login and Logout example using sessions.

Program to create simple Login and Logout example using sessions. ✡️login.php  <html>  <head>  <title>Login Form</title>  </head>  <body>  <h2>Login Form</h2>  <form method="post"   action="checklogin.php"> User Id: <input type="text" name="uid"> <br> Password: <input type="password" name="pw"> <br> <input type="submit" value="Login"> </form> </body> </html> ✡️ checklogin.php  <?php  $uid = $_POST['uid'];  $pw = $_POST['pw']; if($uid == 'arun' and $pw == 'arun123') {  session_start(); $_SESSION['sid']=session_id();              header("location:securepage.php");  } ?> ✡️securepage.php  <?php session_start();  if($_SESSION['sid']==session_id())  {         echo "Welcome to you<br>";     

PHP program to separate odd and even elements from array without using loop

<?php $input = array(4, 3, 6, 5, 8, 7, 2); function oddCmp($input) {     return ($input & 1); } function evenCmp($input) {     return !($input & 1); } $odd = array_filter($input, "oddCmp"); $even = array_filter($input, "evenCmp"); $odd = array_values(array_filter($odd)); $even = array_values(array_filter($even)); print"Odd array :\n"; print_r($odd); print"\nEven array :\n"; print_r($even); ?>

Simple PHP calculator

Let's create a simple calculator <?php  if(isset($_POST['sub']))  {   $txt1=$_POST['n1'];                       $txt2=$_POST['n2'];     $oprnd=$_POST['sub'];  if($oprnd=="+")  $res=$txt1+$txt2; else if($oprnd=="-")              $res=$txt1-$txt2; else if($oprnd=="x")        $res=$txt1*$txt2; else if($oprnd=="/")    $res=$txt1/$txt2;  } ?> <form method="post" action=""> Calculator <br> No1:<input name="n1" value="<?php echo $txt1; ?>"> <br> No2:<input name="n2" value="<?php echo $txt2; ?>"> <br> Res:<input name="res" value="<?php echo $res; ?>"> <br> <input type="submit" name="sub" value="+"> <input type="submit" name="sub" value="-"> <input type="submi

How to get a file size in PHP

Hello guys today we are going to write a PHP program to get the size of a file. <?php $myfile = fopen("/home/students/ppp.txt", "w") or die("Unable to open file!"); $txt = "PHP Exercises\n"; fwrite($myfile, $txt); $txt = "from\n"; fwrite($myfile,$txt); $txt = "hello World\n"; fwrite($myfile, $txt); fclose($myfile); echo "Size of the file".filesize("/home/students/ppp.txt")."\n"; ?>

PHP program to list prime numbers

Here is the Program to list the first 15 prime numbers. <?php  $count = 0;  $num = 2;  while ($count < 15 )  {  $div_count=0;  for ( $i=1; $i<=$num; $i++)  {  if (($num%$i)==0)  {  $div_count++;  }  }  if ($div_count<3)  {  echo $num." , ";  $count=$count+1;  }  $num=$num+1; }  ?> 

How to swap numbers in PHP

 Swap two number using third variable program in PHP <?php $a=10; $b=20; echo "Value of a: $a</br>"; echo "Value of b: $b</br>";        $temp=$a; $a=$b; $b=$temp; echo "Value of a: $a</br>"; echo "Value of b: $b</br>"; ?> Output: Value of a: 10 Value of b: 20 Value of a: 20 Value of b: 10

PHP Strings

Hello guys, Welcome to our next tutorial, Today we are going to learn how to create a php string. <?php $variable = “name”; $literally = ‘My $variable will not print!\\n’; print($literally); $literally = “My $variable will print!\\n”; print($literally); ?> This will produce following result: My name will not print! My name will print

Introduction to PHP

PHP: Hypertext Preprocessor is a general-purpose programming language originally designed for web development. It was originally created by Rasmus Lerdorf in 1994; the PHP reference implementation is now produced by The PHP Group.   Read More Stable release:  7.3.11  /  October 24, 2019 ; 1 day ago Preview release:  7.4.0  RC4  /  October 18, 2019 ; 7 days ago Implementation language:  C  (primarily; some components  C++ ) Developer:  The PHP Development Team,  Zend Technologies Typing discipline:  Dynamic, weak since version 7.0:  Gradual Designed by:  Rasmus Lerdorf The php code can be embedded into html code just as an example given below - basic.php <html> <head> <title> Basic Example </title> </head> <body> <?php echo "This is php code embedded into html"; ?> </body> </html> similarly html code can be embedded in php code as follows - ex