Installing and Setting Up PHP

Before you can start writing PHP code, you need to install a local development environment. The most common setup is using XAMPP, WAMP, or MAMP, which includes PHP, a web server (Apache), and a database (MySQL). Alternatively, you can use Docker or a cloud-based IDE like Cloud9.

Step 1: Download and Install XAMPP

  1. Visit the XAMPP website and download the appropriate version for your operating system.
  2. Run the installer and follow the on-screen instructions.
  3. During installation, make sure to select the PHP component.

Step 2: Start the Apache and MySQL Servers

  1. Open the XAMPP control panel.
  2. Click the Start button for Apache and MySQL.
  3. You should see their status change to Running.

Step 3: Create Your First PHP File

  1. Navigate to the htdocs folder in your XAMPP installation directory (e.g., C:\xampp\htdocs).
  2. Create a new folder named my_php_project.
  3. Inside this folder, create a file named index.php.
  4. Open the file in a text editor and add the following code:
<?php
echo "Hello, World!";
?>

Step 4: Run the Script

  1. Open your web browser and go to http://localhost/my_php_project/index.php.
  2. You should see the output: Hello, World!

Basic PHP Syntax and Concepts

PHP scripts are enclosed within <?php and ?> tags. The code inside these tags is executed on the server, and the result is sent to the client's browser as plain HTML.

Variables and Data Types

PHP supports several data types, including:

TypeDescription
intInteger values
floatFloating point numbers
stringTextual data
booleanTrue or false values
arrayA collection of values
objectInstances of classes
nullRepresents no value

Example:

<?php
$age = 25;         // integer
$price = 19.99;    // float
$name = "John";    // string
$isStudent = true; // boolean
?>

Conditional Statements

PHP supports standard conditional logic using if, else, and switch statements.

<?php
$hour = date("H");

if ($hour < 12) {
    echo "Good morning!";
} elseif ($hour < 18) {
    echo "Good afternoon!";
} else {
    echo "Good evening!";
}
?>

Loops

PHP provides several loop structures, including for, while, and foreach.

<?php
// For loop
for ($i = 1; $i <= 5; $i++) {
    echo "Number: $i<br>";
}

// While loop
$i = 1;
while ($i <= 5) {
    echo "Number: $i<br>";
    $i++;
}

// Foreach loop
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
    echo "Fruit: $fruit<br>";
}
?>

Learn more with official resources