Introduction
PHP is a popular server-side scripting language designed specifically for web development. It is also used as a general-purpose programming language. PHP is widely used due to its interactive features, great HTML and database integration support, and easy to learn.
Prerequisites
- Basic knowledge of HTML
- A computer running Windows, Linux, or macOS
- A text editor (Sublime Text, Notepad++, Atom, etc.)
- A web browser for testing
- XAMPP/WAMP (For Windows) or MAMP (For macOS) or LAMP (For Linux)
1. Install a local server
For PHP to run, you need to install a local server. One of the most commonly used local servers is XAMPP. You can download it from the official website https://www.apachefriends.org/index.html. Once downloaded, follow the installation wizard to install it.
2. Write Your First PHP Script
Open your text editor and type the following:
<?php
echo "Hello, World!";
?>
Save this file as index.php
in the htdocs
directory of your XAMPP installation.
3. Run Your PHP Script
Start the XAMPP Control Panel and start the Apache server. Now, open your web browser and type http://localhost/index.php
in the address bar. You should see "Hello, World!" displayed.
Key PHP Concepts:
Variables
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.
<?php
$txt = "Hello, World!";
echo $txt;
?>
Arrays
An array stores multiple values in one single variable.
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0];
?>
Functions
A function is a block of statements that can be used repeatedly in a program.
<?php
function writeMsg() {
echo "Hello, World!";
}
writeMsg(); // call the function
?>
Conditionals
PHP supports conditional statements like if, else, and elseif to perform different actions based on different conditions.
<?php
function writeMsg() {
echo "Hello, World!";
}
writeMsg(); // call the function
?>
Loops: PHP for loops are used when you know how many times the script should run.
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Conclusion
And much more! PHP has many built-in functions for performing operations on strings, arrays, etc. It is a feature-rich language and provides a wide range of tools for web development. Once you've learned the basics, you can start exploring its advanced features and frameworks like Laravel, Symphony, etc. Happy coding!