Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
283 views

Write A PHP Program To Exchange The First and Last Characters in A Given String and Return The New String

The document contains examples of PHP programs that demonstrate various programming concepts: 1. Exchanging the first and last characters of a string. 2. Printing "Fizz", "Buzz", or "FizzBuzz" for multiples of 3, 5, or both from 1 to 50. 3. Displaying a country-capital array sorted by capital in a HTML table. 4. Accepting form input on one page and displaying it on another. 5. Performing CRUD operations on a MySQL database with a form for data entry. 6. Additional examples include counting word frequencies, user registration/login forms, and a program that counts positive, negative and zero numbers entered using a do
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
283 views

Write A PHP Program To Exchange The First and Last Characters in A Given String and Return The New String

The document contains examples of PHP programs that demonstrate various programming concepts: 1. Exchanging the first and last characters of a string. 2. Printing "Fizz", "Buzz", or "FizzBuzz" for multiples of 3, 5, or both from 1 to 50. 3. Displaying a country-capital array sorted by capital in a HTML table. 4. Accepting form input on one page and displaying it on another. 5. Performing CRUD operations on a MySQL database with a form for data entry. 6. Additional examples include counting word frequencies, user registration/login forms, and a program that counts positive, negative and zero numbers entered using a do
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

1.

Write a PHP program to exchange the first and last characters in a given string and return the
new string. Sample Input: "abcd" Sample Input: dbca

<?php

$string = "abcd";

$length = strlen($string);

$temp = $string[0];

$string[0] = $string[$length-1];

$string[$length-1] = $temp;

echo $string;

?>

The output will be "dbca".

2. . Write a PHP program which iterates the integers from 1 to 50. For multiples of three print
"Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which
are multiples of both three and five print "FizzBuzz".

<?php

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

if ($i % 3 == 0 && $i % 5 == 0) {

echo "FizzBuzz";

} elseif ($i % 3 == 0) {

echo "Fizz";

} elseif ($i % 5 == 0) {

echo "Buzz";

} else {

echo $i;

echo "<br>";

?>
3. Create a PHP script which displays the capital and country name from the above array $ceu.
Sort the list by the capital of the country and display it in a table.
$ceu=array("Italy"=>"Rome","Belgium"=>"Brussels","Denmark"=>"Copenhagen")

<?php
$ceu = array("Italy" => "Rome", "Belgium" => "Brussels", "Denmark" => "Copenhagen");
asort($ceu); //sorting the array by capital
echo "<table><tr><th>Country</th><th>Capital</th></tr>";
foreach ($ceu as $country => $capital) {
echo "<tr><td>$country</td><td>$capital</td></tr>";
}
echo "</table>";
?>

4. Create a simple HTML form and accept the user name,age and hobbies and display the
name on another html page.

<!DOCTYPE html>
<html>
<head>
<title>User Info</title>
</head>
<body>
<form action="display.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age"><br><br>
<label for="hobbies">Hobbies:</label>
<textarea id="hobbies" name="hobbies"></textarea><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

<!-- display.php -->

<!DOCTYPE html>
<html>
<head>
<title>User Info</title>
</head>
<body>
<h1>User Information</h1>
<p>Name: <?php echo $_POST["name"]; ?></p>
</body>
</html>
5. Write a PHP script to perform CRUD operations on MYSQL database by taking user input in a
HTML form with fields name, age, gender, course.

<!-- index.php -->

<!DOCTYPE html>
<html>
<head>
<title>CRUD Operations</title>
</head>
<body>
<h1>Student Information</h1>
<form action="create.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age"><br><br>
<label for="gender">Gender:</label>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br><br>
<label for="course">Course:</label>
<select id="course" name="course">
<option value="B.Tech">B.Tech</option>
<option value="MBA">MBA</option>
<option value="BCA">BCA</option>
<option value="MCA">MCA</option>
</select><br><br>
<input type="submit" value="Create">
</form>

<h1>Update Student Information</h1>


<form action="update.php" method="post">
<label for="id">ID:</label>
<input type="number" id="id" name="id"><br><br>
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age"><br><br>
<label for="gender">Gender:</label>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br><br>
<label for="course">Course:</label>
<select id="course" name="course">
<option value="B.Tech">B.Tech</option>
<option value="MBA">MBA</option>
<option value="BCA">BCA</option>
<option value="MCA">MCA</option>
</select><br><br>
<input type="submit" value="Update">
</form>

<h1>Delete Student Information</h1>


<form action="delete.php" method="post">
<label for="id">ID:</label>
<input type="number" id="id" name="id"><br><br>
<input type="submit" value="Delete">
</form>

<h1>View Student Information</h1>


<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Course</th>
</tr>

<?php
include 'config.php';

$sql = "SELECT * FROM students";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["id"] . "</td>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>" . $row["age"] . "</td>";
echo "<td>" . $row["gender"] . "</td>";
echo "<td>" . $row["course"] . "</td>";
echo "</tr>";
}
} else {
echo "0 results";
}

$conn->close();
?>
</table>
</body>
</html>

<!-- config.php -->

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>

<!-- create.php -->

<?php
include 'config.php';

$name = $_POST["name"];
$age = $_POST["age"];
$gender = $_POST["gender"];
$course = $_POST["course"];

$sql = "INSERT INTO students (name, age, gender, course) VALUES ('$name', '$age',
'$gender', '$course')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

<!-- update.php -->

<?php
include 'config.php';

$id = $_POST["id"];
$name = $_POST["name"];
$age = $_POST["age"];
$gender = $_POST["gender"];
$course = $_POST["course"];

$sql = "UPDATE students SET name='$name', age='$age', gender='$gender',


course='$course' WHERE id='$id'";

if ($conn->query($sql) === TRUE) {


echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

<!-- delete.php -->

<?php
include 'config.php';

$id = $_POST["id"];

$sql = "DELETE FROM students WHERE id='$id'";

if ($conn->query($sql) === TRUE) {


echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}

$conn->close();
?>

6. Write a function countWords ($str) that takes any string of characters and finds the
Number of times each word occurs. You should ignore the distinction between capital and
lowercase letters.
6. Create a Registration form and Login form with database connectivity using PHP.
Here's an example of a registration form and login form with database connectivity using
PHP:

Registration Form:

<form method="post" action="register.php">


<label for="username">Username:</label>
<input type="text" name="username" id="username" required>
<br>
<label for="password">Password:</label>
<input type="password" name="password" id="password" required>
<br>
<label for="confirm_password">Confirm Password:</label>
<input type="password" name="confirm_password" id="confirm_password" required>
<br>
<input type="submit" value="Register">
</form>

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];

// Check if passwords match


if ($password != $confirm_password) {
echo "Passwords do not match";
exit;
}

// Connect to database
$conn = mysqli_connect('localhost', 'username', 'password', 'database_name');

// Check if username already exists


$query = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
echo "Username already exists";
exit;
}

// Insert new user into database


$query = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
if (mysqli_query($conn, $query)) {
echo "User registered successfully";
} else {
echo "Error: " . mysqli_error($conn);
}

mysqli_close($conn);
}
?>

Login Form:

<form method="post" action="login.php">


<label for="username">Username:</label>
<input type="text" name="username" id="username" required>
<br>
<label for="password">Password:</label>
<input type="password" name="password" id="password" required>
<br>
<input type="submit" value="Login">
</form>

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];

// Connect to database
$conn = mysqli_connect('localhost', 'username', 'password', 'database_name');

// Check if username and password match


$query = "SELECT * FROM users WHERE username='$username' AND
password='$password'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
echo "Login successful";
} else {
echo "Invalid username or password";
}

mysqli_close($conn);
}
?>
7. Write a program to enter numbers till the user wants. At the end it should display the count
of positive, negative and zeros entered. (Using do-while loop)

<?php

$positive = 0;

$negative = 0;

$zero = 0;

do {

$num = readline("Enter a number (type 'stop' to exit): ");

if ($num > 0) {

$positive++;

} elseif ($num < 0) {

$negative++;

} else {

$zero++;

} while ($num != 'stop');

echo "Positive numbers: $positive\n";

echo "Negative numbers: $negative\n";

echo "Zeroes: $zero\n";

?>
8. Write a program to compute net amount from the given quantity purchased and rate per
quantity. Discount @10% is allowed if the quantity purchased exceeds 100.
<?php
$quantity = readline("Enter quantity purchased: ");
$rate = readline("Enter rate per quantity: ");

$amount = $quantity * $rate;

if ($quantity > 100) {


$discount = 0.1 * $amount;
$amount -= $discount;
}

echo "Net amount: $amount";


?>

10. Write a Menu-Driven program to implement a calculator which performs only addition,
subtraction, multiplication and division. The operation should happen based on the user choice. (use
switch case)

Here's a possible implementation in PHP:

php

<?php

function add($a, $b) {

return $a + $b;

function subtract($a, $b) {

return $a - $b;

function multiply($a, $b) {

return $a * $b;

function divide($a, $b) {

if ($b == 0) {
echo "Error: division by zero\n";

return null;

} else {

return $a / $b;

while (true) {

echo "Calculator Menu\n";

echo "1. Add\n";

echo "2. Subtract\n";

echo "3. Multiply\n";

echo "4. Divide\n";

echo "5. Quit\n";

$choice = readline("Enter your choice (1-5): ");

if ($choice == "1") {

$a = readline("Enter the first number: ");

$b = readline("Enter the second number: ");

$result = add($a, $b);

echo "Result: $result\n";

} elseif ($choice == "2") {

$a = readline("Enter the first number: ");

$b = readline("Enter the second number: ");

$result = subtract($a, $b);

echo "Result: $result\n";

} elseif ($choice == "3") {

$a = readline("Enter the first number: ");

$b = readline("Enter the second number: ");

$result = multiply($a, $b);


echo "Result: $result\n";

} elseif ($choice == "4") {

$a = readline("Enter the first number: ");

$b = readline("Enter the second number: ");

$result = divide($a, $b);

if ($result !== null) {

echo "Result: $result\n";

} elseif ($choice == "5") {

break;

} else {

echo "Invalid choice\n";

?>

11. Create a form with one text field and submit buttons for string length, string reverse and
uppercase, lowercase, string replace. Display the result accordingly

Here's an example of a form that allows users to perform various string operations:

html

<!DOCTYPE html>

<html>

<head>

<title>String Operations</title>

</head>

<body>

<h1>String Operations</h1>

<form method="post">

<label for="input">Enter a string:</label>

<input type="text" name="input" id="input">


<br>

<input type="submit" name="length" value="String Length">

<input type="submit" name="reverse" value="String Reverse">

<input type="submit" name="uppercase" value="Uppercase">

<input type="submit" name="lowercase" value="Lowercase">

<input type="submit" name="replace" value="String Replace">

</form>

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$input = $_POST["input"];

if (isset($_POST["length"])) {

echo "<p>Length: " . strlen($input) . "</p>";

} elseif (isset($_POST["reverse"])) {

echo "<p>Reverse: " . strrev($input) . "</p>";

} elseif (isset($_POST["uppercase"])) {

echo "<p>Uppercase: " . strtoupper($input) . "</p>";

} elseif (isset($_POST["lowercase"])) {

echo "<p>Lowercase: " . strtolower($input) . "</p>";

} elseif (isset($_POST["replace"])) {

echo "<form method='post'>";

echo "<label for='search'>Search for:</label>";

echo "<input type='text' name='search' id='search'>";

echo "<br>";

echo "<label for='replace'>Replace with:</label>";

echo "<input type='text' name='replace' id='replace'>";

echo "<br>";

echo "<input type='hidden' name='input' value='$input'>";

echo "<input type='submit' value='Replace'>";

echo "</form>";
}

if (isset($_POST["search"]) && isset($_POST["replace"])) {

$search = $_POST["search"];

$replace = $_POST["replace"];

$input = $_POST["input"];

$output = str_replace($search, $replace, $input);

echo "<p>String Replace: " . $output . "</p>";

?>

</body>

</html>

The form has one text input field for the user to enter a string, and five submit buttons for the
different operations. When the user submits the form, the PHP code checks which button was clicked
and performs the corresponding operation on the input string.

For the "String Replace" operation, clicking the button displays another form with two text input
fields for the search and replace strings. When the user submits this form, the PHP code uses the
`str_replace` function to replace all occurrences of the search string with the replace string in the
original input string.

The results of each operation are displayed below the form as HTML paragraphs.

12. Write a PHP program to select data and show it in table format.

Assuming that you have a database with some data that you want to display in a table format, here's
an example PHP program that selects the data and shows it in an HTML table:

php

<!DOCTYPE html>

<html>

<head>
<title>Table Example</title>

</head>

<body>

<h1>Table Example</h1>

<table border="1">

<tr>

<th>ID</th>

<th>Name</th>

<th>Email</th>

<th>Phone</th>

</tr>

<?php

// Connect to the database

$servername = "localhost";

$username = "username";

$password = "password";

$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

// Select data from the table

$sql = "SELECT id, name, email, phone FROM customers";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

while ($row = $result->fetch_assoc()) {


echo "<tr>";

echo "<td>" . $row["id"] . "</td>";

echo "<td>" . $row["name"] . "</td>";

echo "<td>" . $row["email"] . "</td>";

echo "<td>" . $row["phone"] . "</td>";

echo "</tr>";

} else {

echo "<tr><td colspan='4'>No data found</td></tr>";

$conn->close();

?>

</table>

</body>

</html>

The program first connects to the database using the `mysqli` class. You'll need to replace the
placeholders for the server name, username, password, and database name with your own values.

Next, it selects all the data from a table named "customers" using a SQL query. If there's data in the
result set, the program loops through each row and displays the values in an HTML table row. If
there's no data, it displays a message in a single table cell that spans all four columns.

Note that this program is just an example and doesn't include any security measures such as input
validation or prepared statements. In a real-world application, you should always validate user input
and use prepared statements to prevent SQL injection attacks.

13. Write a program that keeps track of how many times a visitor has loaded the page.

Here's an example PHP program that keeps track of how many times a visitor has loaded the page
using cookies:
php

<!DOCTYPE html>

<html>

<head>

<title>Page Visit Counter</title>

</head>

<body>

<h1>Page Visit Counter</h1>

<?php

// Check if the cookie is set

if (isset($_COOKIE["visit_count"])) {

$visit_count = $_COOKIE["visit_count"] + 1;

} else {

$visit_count = 1;

// Set the cookie with the new visit count

setcookie("visit_count", $visit_count, time() + (86400 * 30), "/"); // Cookie lasts for 30 days

echo "<p>You have visited this page $visit_count time(s).</p>";

?>

</body>

</html>

The program first checks if a cookie named "visit_count" is set. If it is, it retrieves its value and
increments it by 1. If it isn't set, it sets the value to 1.

Next, it sets the cookie with the new visit count and a duration of 30 days. Finally, it displays a
message to the visitor with the current visit count.
Note that this program uses cookies to keep track of the visit count, which means that if the visitor
clears their cookies or uses a different browser/device, the count will start over. If you need to keep
track of visits across different sessions or devices, you'll need to use a different method such as
storing the count in a database.

14. Write a program to Develop student registration form and display all the submitted data on
another page

I'm sorry, as an AI language model, I cannot write a complete code for you. However, I can provide
you with a sample code to help you get started with developing a student registration form and
displaying the submitted data on another page using PHP.

HTML Form:

<form action="submit.php" method="post">

<label for="name">Name:</label>

<input type="text" id="name" name="name" required>

<br>

<label for="email">Email:</label>

<input type="email" id="email" name="email" required>

<br>

<label for="phone">Phone Number:</label>

<input type="tel" id="phone" name="phone" required>

<br>

<label for="address">Address:</label>

<textarea id="address" name="address"></textarea>

<br>

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

</form>

PHP Script (submit.php):


<?php

// Retrieve submitted data

$name = $_POST['name'];

$email = $_POST['email'];

$phone = $_POST['phone'];

$address = $_POST['address'];

// Validate data

if (strlen($name) < 2) {

echo "Name must be at least 2 characters long.";

exit;

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

echo "Invalid email address.";

exit;

if (!preg_match('/^[0-9]{10}$/', $phone)) {

echo "Invalid phone number.";

exit;

// Store data in a file or database

$file = fopen('data.txt', 'a');

fwrite($file, "$name,$email,$phone,$address\n");

fclose($file);

// Redirect to new page

header('Location: display.php');
exit;

?>

PHP Script (display.php):

<?php

// Retrieve stored data

$file = fopen('data.txt', 'r');

echo "<table>";

echo "<tr><th>Name</th><th>Email</th><th>Phone Number</th><th>Address</th></tr>";

while (($line = fgets($file)) !== false) {

$data = explode(',', $line);

echo "<tr><td>$data[0]</td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td></tr>";

echo "</table>";

fclose($file);

?>

Note that this is just a sample code and you may need to modify it to fit your specific requirements.
Additionally, you should always sanitize and validate user input to prevent security vulnerabilities
such as SQL injection or cross-site scripting (XSS).

15. Write a PHP program to select data and show into table format.

Assuming you have a database with some data, you can use the following PHP code to select the
data and display it in a table format:

<?php

// Connect to database

$servername = "localhost";
$username = "username";

$password = "password";

$dbname = "database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

// Select data from table

$sql = "SELECT id, name, email, phone FROM students";

$result = $conn->query($sql);

// Display data in table format

if ($result->num_rows > 0) {

echo "<table>";

echo "<tr><th>ID</th><th>Name</th><th>Email</th><th>Phone</th></tr>";

while($row = $result->fetch_assoc()) {

echo "<tr><td>" . $row["id"] . "</td><td>" . $row["name"] . "</td><td>" . $row["email"] .


"</td><td>" . $row["phone"] . "</td></tr>";

echo "</table>";

} else {

echo "No results found.";

// Close database connection

$conn->close();

?>
Replace `localhost`, `username`, `password`, and `database_name` with your actual database
credentials. Also, replace `students` with the name of your table containing the data.

This code selects the `id`, `name`, `email`, and `phone` columns from the `students` table and
displays them in a table format. If no results are found, it displays a message saying so.

Note that you should always sanitize and validate user input to prevent security vulnerabilities such
as SQL injection or cross-site scripting (XSS).

16. Write a program to read customer information like c_no, c_name, item purchased and mob_no
from customer table and display all this information in table format on output screen.

Assuming you have a database named `mydatabase` with a table named `customer` containing the
columns `c_no`, `c_name`, `item_purchased`, and `mob_no`, you can use the following PHP code to
select the data and display it in a table format:

<?php

// Connect to database

$servername = "localhost";

$username = "username";

$password = "password";

$dbname = "mydatabase";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

// Select data from table

$sql = "SELECT c_no, c_name, item_purchased, mob_no FROM customer";


$result = $conn->query($sql);

// Display data in table format

if ($result->num_rows > 0) {

echo "<table>";

echo "<tr><th>Customer Number</th><th>Name</th><th>Item Purchased</th><th>Mobile


Number</th></tr>";

while($row = $result->fetch_assoc()) {

echo "<tr><td>" . $row["c_no"] . "</td><td>" . $row["c_name"] . "</td><td>" .


$row["item_purchased"] . "</td><td>" . $row["mob_no"] . "</td></tr>";

echo "</table>";

} else {

echo "No results found.";

// Close database connection

$conn->close();

?>

This code selects the `c_no`, `c_name`, `item_purchased`, and `mob_no` columns from the
`customer` table and displays them in a table format. If no results are found, it displays a message
saying so.

Note that you should always sanitize and validate user input to prevent security vulnerabilities such
as SQL injection or cross-site scripting (XSS).

17. Write a PHP script to convert uppercase string to lowercase & Write a PHP script split the
following string.

To convert an uppercase string to lowercase in PHP, you can use the `strtolower()` function. Here's an
example:
<?php

$uppercaseString = "THIS IS AN UPPERCASE STRING";

$lowercaseString = strtolower($uppercaseString);

echo $lowercaseString; // Output: this is an uppercase string

?>

To split a string in PHP, you can use the `explode()` function. This function splits a string into an array
based on a specified delimiter. Here's an example:

<?php

$string = "apple,banana,orange";

$array = explode(",", $string);

print_r($array); // Output: Array ( [0] => apple [1] => banana [2] => orange )

?>

In this example, the `explode()` function splits the string `$string` into an array using the comma `,` as
the delimiter. The resulting array `$array` contains three elements: `apple`, `banana`, and `orange`.
The `print_r()` function is used to display the contents of the array.

18. Write a PHP script to calculate and print the factorial of a number using a for loop.

1. <?php
2. $num = 4;
3. $factorial = 1;
4. for ($x=$num; $x>=1; $x--)
5. {
6. $factorial = $factorial * $x;
7. }
8. echo "Factorial of $num is $factorial";
9. ?>
19. 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";
?>
20. Write a PHP script to display string, values within a table

<?php
$a=1000;
$b=1400;
$c=1900;
$d=1800;

echo "<table border=1 cellspacing=0 cellpading=0>


<tr> <td>Salary of Mr. David</td> <td>$a$</font></td></tr>
<tr> <td>Salary of Mr. John</td> <td>$b$</font></td></tr>
<tr> <td>Salary of Mr. Michael</td> <td>$c$</font></td></tr>
<tr> <td>Salary of Mr. Matthew</td> <td>$d$</font></td></tr>
</table>";
?>

21. Write a simple PHP program to check that email id is valid or not.

<?php
// pass valid/invalid emails
$email = "mail@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo '"' . $email . '" = Valid'."\n";
}
else
{
echo '"' . $email . '" = Invalid'."\n";
}
?>
22. Write a PHP script using nested for loop that creates a chess board.

<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>

<table width="300px" cellspacing="0px" cellpadding="0px" border="1px">

<?php
for($row=1;$row<=8;$row++)
{
echo "<tr>";
for($col=1;$col<=8;$col++)
{
$total=$row+$col;
if($total%2==0)
{
echo "<td height=30px width=30px bgcolor=white></td>";
}
else
{
echo "<td height=30px width=30px bgcolor=black></td>";
}
}
echo "</tr>";
}
?>
</table>
</body>
</html>
23. 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].", ";
}
?>
24. Write a PHP program to print out the multiplication table upto 5*10.

<?php

for ($i = 5; $i < 11; $i++) {

for ($j = 5; $j < 11; $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";

?>

25. Write a PHP script to print letters from ‘a’ to ‘z’.

<?php
for ($x = ord('a'); $x <= ord('z'); $x++)
echo chr($x);
echo "\n"
?>
26. Write a PHP script to sort an array in reverse order (highest to lowest).

<?php

$numbers = array(5, 2, 8, 3, 9, 1);

rsort($numbers);

echo "<ul>";

foreach($numbers as $number){

echo "<li>$number</li>";

echo "</ul>";

?>
27. Write a PHP script which will display the Cars in the following way using array.

<?php

$cars = array("Volvo", "BMW", "Toyota", "Honda");

echo "<ul>";

foreach($cars as $car){

echo "<li>$car</li>";

echo "</ul>";

?>

Output:

- Volvo

- BMW

- Toyota

- Honda

28. Write a PHP script to calculate and print the factorial of a number using a for loop.

<?php

$num = 5;

$factorial = 1;

for($i=$num; $i>=1; $i--){

$factorial *= $i;

echo "Factorial of $num is: $factorial";

?>

Output: Factorial of 5 is: 120


29. Write a PHP script to extract the user name from the email ID

<?php

$email = "exampleuser@example.com";

$username = substr($email, 0, strpos($email, "@"));

echo $username;

?>

Output: exampleuser

30. Write a PHP script which displays all the numbers between 50 and 150 that are divisible by 4
<?php

for($i=50;$i<=150;$i++){

if($i%4==0){

echo $i." ";

?>

You might also like