PHP, short for PHP: Hypertext Preprocessor, stands out in the realm of web development. It’s a server-side scripting language, which means it can generate dynamic page content. For newcomers, understanding the syntax can be a stepping stone towards mastering PHP.
PHP Start and End Tags
To commence writing PHP, you’ll need to know the opening and closing tags. They tell the server where PHP code starts and ends.
Opening Tag: <?php
Closing Tag: ?>
In between these tags, you insert your PHP code.
Comments in PHP
Comments help developers remember what certain lines of code do. Plus, they’re handy for collaborators.
- Single-line Comment:
// This is a comment
- Multi-line Comment:
/* This is a multi-line comment */
PHP Echo and Print Statements
Displaying data to the screen is fundamental. PHP provides two ways: echo
and print
.
Echo Statement
Echo
is more popular and versatile:
<?php echo "Hello, World!"; ?>
Print Statement
Print
works similarly:
<?php print "Hello, World!"; ?>
Variables in PHP
Storing data values is crucial. In PHP, you use variables for that.
Example:
<?php $text = "Hello, World!"; echo $text; ?>
Variables start with a $
followed by the variable name. Names are case-sensitive.
PHP Data Types
Understanding PHP’s primary data types ensures effective coding. They include:
- Strings – sequences of characters, like “Hello!”
- Integers – whole numbers, such as 1, 2, or 3.
- Floats – numbers with a decimal point, like 1.23.
- Booleans – True or False values.
- Arrays – hold multiple values.
PHP If…Else… Statements
Decision-making in code? Use If…Else statements.
<?php
$weather = "rainy";
if ($weather == "sunny") {
echo "It's a sunny day!";
} elseif ($weather == "rainy") {
echo "Carry an umbrella!";
} else {
echo "It's a pleasant day!";
}
?>
PHP Loops
To execute code multiple times, employ loops.
Types include:
- While Loop – while a condition is true, run.
- For Loop – run a code a specific number of times.
- Foreach Loop – used with arrays.
PHP Functions
Functions are blocks of code that perform a specific task. PHP offers predefined functions and lets you create custom ones.
Example of a Custom Function:
<?php
function greet() {
echo "Hello, World!";
}
greet(); // Calls the function
?>
Understanding basic PHP syntax forms the foundation for web development using this language. From setting up variables to creating custom functions, each step you take familiarizes you more with its power and versatility.