Here’s a short practical exercise to help you get started with PHP:
- Create a new directory for your PHP project and navigate to it in your terminal or command prompt.
- Create a new file named
index.php
and open it in your text editor or IDE. - Add the following code to the
index.php
file:
phpCopy code<!DOCTYPE html>
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
$fruits = array("apple", "banana", "cherry", "orange");
sort($fruits);
foreach ($fruits as $fruit) {
echo "$fruit <br>";
}
?>
</body>
</html>
- Save the file and open your web browser. Type the URL of your project into the address bar, for example,
http://localhost/my-project/index.php
. You should see a list of fruits sorted in alphabetical order. - Now, let’s modify the code to add a form to the page that allows the user to enter a new fruit. Replace the code in
index.php
with the following:
phpCopy code<!DOCTYPE html>
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<form action="index.php" method="post">
Fruit: <input type="text" name="fruit">
<input type="submit">
</form>
<br>
<?php
if (isset($_POST['fruit'])) {
$fruit = $_POST['fruit'];
$fruits[] = $fruit;
sort($fruits);
} else {
$fruits = array("apple", "banana", "cherry", "orange");
}
foreach ($fruits as $fruit) {
echo "$fruit <br>";
}
?>
</body>
</html>
- Save the file and refresh the page in your browser. You should now see a form that allows you to enter a new fruit, and after submitting the form, the new fruit should be added to the list and displayed below the form in alphabetical order.
In this practical, you’ve learned how to create a dynamic PHP web page that allows the user to enter and display data. You’ve also learned how to use PHP arrays and how to handle form submissions. This is just a simple example of what you can do with PHP, and you can now start building more complex and sophisticated web applications.