PHP – Syntax
PHP, which stands for Hypertext Preprocessor, is a versatile scripting language used primarily for web development. Understanding the syntax of PHP is essential for creating dynamic and interactive web pages. In this article, we’ll explore the fundamental syntax of PHP along with examples to illustrate each concept.
Basic Syntax
PHP code is embedded within HTML markup using special tags. The most common way to denote PHP code is by enclosing it within <?php
and ?>
tags. For example:
0 1 2 3 4 5 6 7 |
<?php // PHP code goes here echo "Hello, World!"; ?> |
In the above example, echo
is a PHP function used to output text to the browser.
Variables and Data Types
Variables in PHP are declared using the $
symbol followed by the variable name. PHP supports various data types, including integers, floats, strings, booleans, arrays, and objects. Here’s an example of variable declaration and assignment:
0 1 2 3 4 5 6 7 8 |
<?php $name = "John"; $age = 25; $is_student = true; ?> |
In this example, $name
is a string variable, $age
is an integer variable, and $is_student
is a boolean variable.
Control Structures
PHP supports various control structures like if-else statements, loops, and switch-case statements.
If-Else Statement
The if-else statement is used to execute code conditionally based on a given condition. Here’s an example:
0 1 2 3 4 5 6 7 8 9 10 11 12 |
<?php $grade = 85; if ($grade >= 60) { echo "Pass"; } else { echo "Fail"; } ?> |
Loops
PHP supports different types of loops such as for
, while
, and foreach
. Here’s an example of a for
loop:
0 1 2 3 4 5 6 7 8 |
<?php for ($i = 1; $i <= 5; $i++) { echo "Number: $i <br>"; } ?> |
Switch-Case Statement
The switch-case statement is used to perform different actions based on different conditions. Here’s an example:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $day = "Monday"; switch ($day) { case "Monday": echo "Today is Monday"; break; case "Tuesday": echo "Today is Tuesday"; break; default: echo "It's neither Monday nor Tuesday"; } ?> |
Functions
Functions in PHP allow you to group code into reusable blocks. You can define your own functions or use built-in functions provided by PHP. Here’s an example of a user-defined function:
0 1 2 3 4 5 6 7 8 9 10 |
<?php function greet($name) { echo "Hello, $name!"; } greet("Alice"); ?> |
Conclusion
Understanding the syntax of PHP is crucial for writing efficient and effective code. In this article, we’ve covered the basic syntax of PHP, including variables, control structures, and functions, along with examples to illustrate each concept. By mastering PHP syntax, you’ll be well-equipped to develop dynamic and interactive web applications.