Basic Structure of PHP

So, you've mastered running a PHP script—awesome! But now you're probably wondering: "How do I actually structure my PHP code?" No worries, my friend! In this guide, we’ll break down the basic structure of PHP so you can write cleaner, more organized code. 

PHP Tags and Syntax

PHP code is enclosed within special tags so the server knows it’s PHP and not just plain HTML.

<?php
  // PHP code goes here
?>

Short Tag (Not Recommended)

You might also see this:

<?
  echo "Hello, World!";
?>

But be careful! Short tags are not always enabled on all servers. Stick to <?php to avoid problems.

Comments in PHP

Comments are used to explain code or temporarily disable parts of it. PHP supports three types of comments:

// This is a single-line comment
# This is also a single-line comment
/* This is a 
   multi-line comment */

Comments are ignored by PHP but are super useful for humans reading the code (including future you!).

Variables and Data Types 

Variables in PHP start with $ and don’t need explicit type declarations.

$name = "John"; // String
$age = 25;       // Integer
$height = 5.9;   // Float
$isCool = true;  // Boolean

Variable Naming Rules:

 Must start with $ Can contain letters, numbers, and underscores (_)  Cannot start with a number ($1name )  No spaces ($full name)

Control Structures

PHP includes conditional statements and loops to control program flow.

If-Else Statement

$age = 18;
if ($age >= 18) {
  echo "You are an adult!";
} else {
  echo "Sorry, you are too young.";
}

Loops

Loops help execute code multiple times.

While Loop

$x = 1;
while ($x <= 5) {
  echo "Number: $x";
  $x++;
}

For Loop

for ($i = 1; $i <= 5; $i++) {
  echo "Number: $i";
}

Functions in PHP

Functions help organize and reuse code.

function greet($name) {
  return "Hello, $name!";
}

echo greet("Alice"); 
 

PHP has a simple but powerful structure that makes it easy to learn and use. Understanding its syntax, variables, control structures, and functions will set you up for success.

Post a Comment

0 Comments