PHP Programs |Basic PHP Programs

1. Write a PHP program to print Hello World

<?php

echo “Hello World”;

?>

Output:

2. Write a PHP program to print your name and address.

<?php

$name = “Eliza Begum”;

$add = “<br> Parbatia <br>  Tinsukia <br>  Assam <br> India”;

print $name;

print $add;

?>

Output:

3. Write a PHP program to print text using print command.

<?php

/*print string*/

print “Hello world”;

/*print variable values*/

$name = “Eliza Begum”;

$roll_no= 1;

print “<br>”;

print “Name: ” . $name . “<br>”. ” Roll Number: ” . $roll_no ;

?>

Output:

4. Write a PHP program to add two numbers.

OR

Write a program to declare two numbers and print the sum of two.

<?php 

$x=17; 

$y=20; 

$z=$x+$y; 

echo “Sum: “, $z; 

?> 

Output:

5. Write a PHP program to perform arithmetic operations.

<?php

$x = 10;

$y = 5;

echo $x+$y.”<br>”;

echo $x-$y.”<br>”;

echo $x*$y.”<br>”;

echo $x/$y.”<br>”;

echo $x%$y;

?>

Output:

6. Write a PHP program using assignment operator.

<?php

$x = 10;

$y = 5;

$x += $y; // Equivalent to: $x = $x + $y;

echo $x . “<br>”;

$x -= $y; // Equivalent to: $x = $x – $y;

echo $x;

?>

Output:

7. Write a PHP a program using comparison operators.

<?php

$x = 10;

$y = 5;

echo $x == $y;

echo $x != $y;

echo $x > $y;

echo $x < $y;

echo $x >= $y;

echo $x <= $y;

?>

Output:

8. Write a PHP program using increment decrement operator.

<?php

$x = 5;

echo ++$x;

echo ” “;

echo $x++; 

echo ” “;

echo – -$x;

echo ” “;

echo $x- -;

?>

Output:

9. Write a PHP program using logical operator.

<?php

$x = true;

$y = false;

echo $x && $y;

echo $x || $y; 

echo !$x;

?>

Output:

10. Write a PHP program using Conditional Operator.

<?php

$x = 10;

$y = ($x > 5) ? “greater than 5” : “less than or equal to 5”;

echo $y;

?>

Output:

11. Write a PHP program to concatenate two strings

<?php

$x= “Hello”;

$x.= ” World”;

echo $x;

?>

Output:

OR

<?php

$x=”Hello”;

$y=$x .” World”;

// now $y contains “Hello World”

echo $y;

?>

Output:

12. Write a PHP program to find the Area of a triangle.

<?php

$base=10;

$height=15;

echo “Area of the triangle is=”,($base* $height)/2;

?>

Output:

Area of the triangle is=75

13. Write a PHP program to swap two variables.

<?php

// Declare and initialize two variables

$a = 15;

$b = 27;

// Display the original values of the variables

echo “\nThe number before swapping is: “;

echo “a =” . $a . ”              b=” . $b;

// Swap Logic

$temp = $a;

$a = $b;

$b = $temp;

// Display the values after swapping

echo “<br><br>The number after swapping is: “;

echo “a =” . $a . ”              b=” . $b;

?>

Output:

14. Write a program to check whether a given number is even or not.

<?php

$number=12;

if($number%2==0)

{

echo “$number is even number” ;

}

else

{

echo “$number is not even number” ;

}

?>

Output:

15. Write a program in PHP to perform switch case to print if a alphabet is a vowel or not.

<?php     

    $ch = ‘E’; 

    switch ($ch) 

    {    

        case ‘A’:  

        case ‘a’:  

            echo “$ch is vowel”; 

            break;

        case ‘E’:                         

        case ‘e’:  

            echo “$ch is vowel”; 

            break;

       case ‘I’:

        case ‘i’:  

            echo “$ch is vowel”; 

            break;

        case ‘O’:                        

        case ‘o’:  

            echo “$ch is vowel”; 

            break; 

        case ‘U’:                        

        case ‘u’:  

            echo “$ch is vowel”; 

            break; 

       default:  

            echo “$ch is not vowel”; 

    } 

?>   

Output:

16. Write a PHP program to print series of numbers from 1 to 100 using for loop.

<?php

for( $i=1; $i<=100; $i++ )

{

echo $i;

echo ” “;

}

?>

Output:

17. Write a PHP program to add two number taking input from user.

<html> 

<body> 

<form method=”post”> 

Enter First Number: 

<input type=”number” name=”number1″ /><br><br> 

Enter Second Number: 

<input type=”number” name=”number2″ /><br><br> 

<input  type=”submit” name=”submit” value=”Add”> 

</form> 

<?php 

    if(isset($_POST[‘submit’])) 

    { 

        $number1 = $_POST[‘number1’]; 

        $number2 = $_POST[‘number2’]; 

        $sum =  $number1+$number2;    

echo “The sum of $number1 and $number2 is: “.$sum;  

?> 

</body> 

</html> 

Output:

Note: Use isset() method in PHP to test the form is submitted successfully or not. In the code, use isset() function to check $_POST[‘submit’] method.

18. Write a program to check whether a given number is even or not taking input from user.

<html> 

<body> 

<form method=”post”> 

Enter a number: 

    <input type=”number” name=”number”> 

    <input type=”submit” value=”Submit”> 

</form> 

</body> 

</html> 

<?php  

    if($_POST){ 

        $number = $_POST[‘number’];  

        if(($number % 2) == 0) { 

            echo “$number is an Even number”; 

        }

else { 

            echo “$number is not even number”; 

        } 

    } 

?>

Output: On entering the number 4, following output appears.

On entering the number 7, following output appears.

19. Write a PHP program to find the factorial of a given number

<?php 

$num = 5; 

$factorial = 1; 

for ($x=$num; $x>=1; $x- -)  

  $factorial = $factorial * $x; 

echo “Factorial of $num is $factorial”; 

?> 

Output:

20. Write a PHP program to find the factorial of any number

<html> 

<head> 

<title>Factorial Program using loop in PHP</title> 

</head> 

<body> 

<form method=”post”> 

    Enter a Number:<br><br>

    <input type=”number” name=”number”> 

    <input type=”submit” value=”Submit” /> 

</form> 

<?php  

    if($_POST){ 

        $fact = 1; 

        //getting value from input text box ‘number’ 

        $number = $_POST[‘number’]; 

        echo “Factorial of $number:<br><br>”; 

        //start loop 

        for ($i = 1; $i <= $number; $i++){        

            $fact = $fact * $i; 

            } 

            echo $fact . “<br>”; 

    } 

?> 

</body> 

</html> 

Output:

21. Write a PHP program using array.

<?php

// Using square brackets

$colors = [“Red”, “Green”, “Blue”];

// Using the array() function

$fruits = array(“Apple”, “Banana”, “Orange”);

// Accessing elements

echo $colors[0];

echo ” “;

echo $fruits[1];

?>

Output:

22. Write a PHP program using Associative Array.

<?php

// Using the array() function

$person = array(“name” => “John”, “age” => 50, “city” => “New York”);

// Using square brackets with key-value pairs

$book = [“title” => ” PHP Programming”, “author” => ” Smith”, “pages” => 300];

// Accessing elements

echo $person[“name”];

echo $book[“author”];

?>

Output:

23. Write a PHP program using multidimensional array

<?php

// Indexed multidimensional array

$matrix = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9] ];

// Associative multidimensional array

$employees = [

[“name” => ” John”, “age” => 30],

[“name” => ” Alice”, “age” => 25],

[“name” => ” Bob”, “age” => 35]

];

// Accessing elements

echo $matrix[0][1];

echo $employees[1][“name”];

?>

Output:

24. Write a PHP program using function

<?php

// Function without parameters

function greet() {

echo “Hello, World!”;

} // Function with parameters

function add($a, $b) {

    return $a + $b; }

// Calling the greet function

greet();

// Calling the add function

$result = add(5, 3);

echo ” <br>Result ” .$result;

?>

Output:

25. Write a PHP program to create a function to find the addition of two integer numbers.

<?php

//function definition

//this function will take two integer arguments

//and return the sum of them

function addTwoNumbers(int $x, int $y)

{

    return $x + $y;

}

//calling the function and printing the result

echo ” sum of 20 and 25 : ” . addTwoNumbers(20, 25);

echo “<br>”;

echo ” sum of 40 and -10: ” . addTwoNumbers(40, -10);

?>

Output:

26. Create a simple HTML form and accept the user name and display the name through PHP echo statement.

<html>

<body>

 <form method=’POST’>

 <h2>Please input your name:</h2>

  <!– Text input field for the name –>

  <input type=”text” name=”name”><br><br>

  <!– Submit button to submit the form –>

  <input type=”submit” name=”submit” value=”Submit”>

   </form>

   <?php

   // Check if the form is submitted and ‘name’ is set in $_POST

   if(isset($_POST[‘submit’])) {

      // Retrieve name from the form and store it in a local variable

      $name = $_POST[‘name’];

      // Display a greeting message with the entered name

      echo “<h3> Hello $name </h3>”;

   }

   ?>

</body>

</html>

Output:

27. Write a PHP program to display string, values within a table.

<?php

$a=1000;

$b=1200;

$c=1400;

echo “<table border=1 cellspacing=5 cellpading=5>

<tr><th>Name</th><th>Salary</th>

<tr> <td>Ajay</td> <td>$a</font></td></tr>

<tr> <td>Priya</td> <td>$b</font></td></tr>

<tr> <td>Leena</td> <td>$c</font></td></tr>

</table>”;

?>

Output:

28. Write a simple PHP program to check that emails are valid.

<?php

// Specify an email address (valid or invalid)

$email = “example@gmail.com”;

// Use the filter_var function with FILTER_VALIDATE_EMAIL to check if the email is valid

if (filter_var($email, FILTER_VALIDATE_EMAIL))

{

    // If the email is valid, print a message indicating it is valid

    echo $email . ‘ is Valid’;

}

else

{

    // If the email is invalid, print a message indicating it is invalid

    echo $email . ‘ is Invalid’;

}

?>

Output:

example@gmail.com is Valid

29.  Write a PHP program to print current date in various formats.
 <?php
/*print date in dd/mm/yy format*/
print “Current date in dd/mm/yy format: ” . date(“d/m/y”);
print “<br>”.”<br>”;
 /*print date in dd/mm/yyyy format*/
print “Current date in dd/mm/yyyy format: ” . date(“d/m/Y”);
print “<br>”.”<br>”;
 /*print date in dd MON yyyy format*/
print “Current date in dd MON yyyy format: ” . date(“d M Y”);
print “<br>”.”<br>”;
 /*print date in Day, dd MON yyyy format*/
print “Current date in Day, dd MON yyyy format: ” . date(“D, d M Y”);
print “<br>”.”<br>”;
 /*print date in Day, dd MONTH yyyy format*/
print “Current date in Day, dd MONTH yyyy format: ” . date(“D, d F Y”);
 ?>

Output:

 Current date in dd/mm/yy format: 07/06/24

Current date in dd/mm/yyyy format: 07/06/2024

Current date in dd MON yyyy format: 07 Jun 2024

Current date in Day, dd MON yyyy format: Fri, 07 Jun 2024

Current date in Day, dd MONTH yyyy format: Fri, 07 June 2024

30. Write a PHP program to print current time in various formats.

<?php
/*print time in HH:MM:SS*/
date_default_timezone_set(“Asia/Calcutta”);
print “Current time in HH:MM:SS format: ” . date(“h:i:s”);
print “<br>”.”<br>”;
 /*print time in HH:MM:SS*/
print “Current time in HH:MM:SS am/pm format: ” . date(“h:i:s a”);
print “<br>”.”<br>”;
 /*print time in HH:MM:SS*/
print “Current time in HH:MM:SS AM/PM format: ” . date(“h:i:s A”);
print “<br>”.”<br>”;
 /*print time in HH:MM:SS*/
print “Current time in HH24:MM:SS format: ” . date(“H:i:s A”);
?>

Output:

Current time in HH:MM:SS format: 10:19:05

Current time in HH:MM:SS am/pm format: 10:19:05 am

Current time in HH:MM:SS AM/PM format: 10:19:05 AM

Current time in HH24:MM:SS format: 10:19:05 AM

31. Write PHP program to get total number of days in a month.

<?php
$curmnth = date(‘m’);
$curyear = date(‘Y’);
function get_days_in_month($month, $year)
{
    if ($month == “02”)
    {
        if ($year % 4 == 0) return 29;
        else return 28;
    }
    else if ($month == “01” || $month == “03” || $month == “05” || $month == “07” || $month == “08” || $month == “10” || $month == “12”) return 31;
    else return 30;
}
$totDays = get_days_in_month($curmnth, $curyear);
printf(“Total no of days in current month : ” . $totDays);
 ?>

Output:

Total no of days in a current month: 30
32. Write a PHP program to display Student Result

First create a Form and named it “StudentDetails.php”

<html>

   <form action=”Result.php”>

      <table>

         <caption>STUDENT MARKSHEET FORM</caption>

         <tr>

            <td>School Name: </td>

            <td><input type=text name=sn size=30></td>

         </tr>

         <tr>

            <td>Student Name: </td>

            <td><input type=text name=stn size=30></td>

         </tr>

         <tr>

            <td>Father’s Name: </td>

            <td><input type=text name=fn size=30></td>

         </tr>

         <tr>

            <td>Dob:</td>

            <td><input type=text name=dob size=30></td>

         </tr>

         <tr>

            <td>Gender:</td>

            <td><input type=radio name=gen size=30 value=”Male”>Male<input type=radio name=gen size=30 value=”Female”>Female</td>

         </tr>

         <tr>

            <td>Hindi marks:</td>

            <td><input type=text name=hin size=30></td>

         </tr>

         <tr>

            <td>English marks:</td>

            <td><input type=text name=eng size=30></td>

         </tr>

         <tr>

            <td>Maths marks:</td>

            <td><input type=text name=math size=30></td>

         </tr>

         <tr>

            <td>Physics marks: </td>

            <td><input type=text name=phy size=30></td>

         </tr>

         <tr>

            <td>Chemistry marks:</td>

            <td><input type=text name=chem size=30></td>

         </tr>

         <tr>

            <td><input type=submit></td>

            <td><input type=reset></td>

         </tr>

      </table>

   </form>

</html>

Output:

To show the result make a file named “Result.php”. Add following code to it:

<html>

<?php

          $sn=$_GET[‘sn’];

          $stn=$_GET[‘stn’];

          $fn=$_GET[‘fn’];

          $dob=$_GET[‘dob’];

          $gender=$_GET[‘gen’];

          $hindi=$_GET[‘hin’];

          $english=$_GET[‘eng’];

          $maths=$_GET[‘math’];

          $physics=$_GET[‘phy’];

          $chemistry=$_GET[‘chem’];

          $total=$hindi+$english+$maths+$physics+$chemistry;

          $remark1=0;

          $remark2=0;

          $remark3=0;

          $remark4=0;

          $remark5=0;

          $count=0;

          $s=”a”;

          $gen=’ ‘;

          $min=35;

          $max=100;

          $hin=’Hindi’;

          $eng=’English’;

          $math=’Maths’;

          $phy=’Physics’;

          $chem=’Chemistry’;

          if($gender==”Male”){

                    $gen=”S/o”;

          }else if($gender==”Female”){

                    $gen=”D/o”;

          }

          if($hindi<35){

                    $remark1=”<font color=’red’>*</font>”;

                    $count++;

                    $s=$s.’ and ‘.$hin;

          } else if($hindi>79) {

                    $remark1=”<font color=’green’>D</font>”;

          } else {

                    $remark1=’-‘;

          }

          if($english<35) {

                    $remark2=”<font color=’red’>*</font>”;

                    $count++;

                    $s=$s.’ and ‘.$eng;

          }else if($english>79) {

                    $remark2=”<font color=’green’>D</font>”;

          } else {

                    $remark2=’-‘;

          }

          if($maths<35) {

                    $remark3=”<font color=’red’>*</font>”;

                    $count++;

                    $s=$s.’ and ‘.$math;

          } else if($maths>79) {

                    $remark3=”<font color=’green’>D</font>”;

          } else {

                    $remark3=’-‘;

          }

          if($physics<35) {

                    $remark4=”<font color=’red’>*</font>”;

                    $count++;

                    $s=$s.’ and ‘.$phy;

          } else if($physics>79) {

                    $remark4=”<font color=’green’>D</font>”;

          } else {

                    $remark4=’-‘;

          }

          if($chemistry<35) {

                    $remark5=”<font color=’red’>*</font>”;

                    $count++;

                    $s=$s.’ and ‘.$chem;

          } else if($chemistry>79) {

                    $remark5=”<font color=’green’>D</font>”;

          } else {

                    $remark5=’-‘;

          }

          $s=str_replace(‘a and’, ”, $s);

          if($count>2) {

                    $s=”Fail”;

          } else if($count==0) {

                    $s=”Pass”;

          } else if($count<=2) {

                    $s=”Compartment in “.’ ‘.$s;

          }

?>

<center>

          <table border=1>

                    <tr>

                    <td>

                              <table  width=100%>

                              <tr>

                                        <td>

                                                  <img src=’images.png’ width=120 height=120>

                                        </td>

                                        <td>

                                                  <b><font size=’5′>CENTRAL BOARD OF HIGHER EDUCATION</font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b><br><br>

                                                  <font size=’4′ color=’grey’><b><?php  echo “$sn”; ?></b></font>

                                        </td>

                              </tr>

                              </table>

                    </td>

                    </tr>

                    <tr>

                    <td>

                              <table width=100%>

                                        <tr><td><font size=’4′><?php echo “$stn”; ?>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<?php echo “$gen”;?>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<?php echo” Mr.$fn”;?></font></td></tr>

                                        <tr><td><font size=’4′><?php echo “$dob”?>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<?php echo”$gender”;?></font></td></tr>

                              </table>

                    </td>

                    </tr>

                    <tr>

                    <td>

                              <table border=1 width=100%>

                                        <tr><th><i>Subject code</i></th><th><i>Subject name</i></th><th><i>Min marks</i></th><th><i>Max marks</i></th><th><i>Marks obtained</i></th><th><i>Remark</i></th></tr>

                              <tr><td>101</td><td>Hindi</td><td>35</td><td>100</td><td><?php echo “$hindi”; ?></td><td><?php echo “$remark1”; ?></td></tr>

                              <tr><td>102</td><td>English</td><td>35</td><td>100</td><td><?php echo “$english”; ?></td><td><?php echo “$remark2”; ?></td></tr>

                              <tr><td>103</td><td>Maths</td><td>35</td><td>100</td><td><?php echo “$maths”; ?></td><td><?php echo “$remark3”; ?></td></tr>

                              <tr><td>104</td><td>Physics</td><td>35</td><td>100</td><td><?php echo “$physics”; ?></td><td><?php echo “$remark4”; ?></td></tr>

                              <tr><td>105</td><td>Chemistry</td><td>35</td><td>100</td><td><?php echo “$chemistry”; ?></td><td><?php echo “$remark5”; ?></td></tr>

                              <tr><td></td><td></td><td><b>Total</b></td><td><b>400</b></td><td><b><?php echo “$total”; ?><b></td><td></td></tr>

                              </table>

                    </td>

                    </tr>

                    <tr>

                    <td>

                              <table>

                                        <tr><td><b><font size=’4′>Result:&nbsp;&nbsp;&nbsp;&nbsp;<?php echo “$s”; ?></font></b></td></tr>

                              </table>

                    </td>

                    </tr>

          </table>

</center>

</html>

Output:

Leave a Comment