PHP's basic syntax is relatively straightforward. A PHP script starts with <?php and ends with ?>. The code written between these tags is executed on the server.
In PHP, variables start with a $ sign followed by the name of the variable. Variable names are case - sensitive.
<?php
$greeting = "Hello, World!";
echo $greeting;
?>
In this example, we declare a variable $greeting and assign it the value "Hello, World!". Then we use the echo statement to output the value of the variable.
Functions in PHP are defined using the function keyword.
<?php
function addNumbers($a, $b) {
return $a + $b;
}
$result = addNumbers(5, 3);
echo $result;
?>
Here, we define a function addNumbers that takes two parameters $a and $b, adds them together, and returns the result. We then call the function with arguments 5 and 3 and store the result in the $result variable.
The if - else statement is used for decision - making in PHP.
<?php
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
?>
This code checks if the value of $age is greater than or equal to 18. If it is, it outputs "You are an adult."; otherwise, it outputs "You are a minor."
The for loop is used when you know in advance how many times you want to execute a block of code.
<?php
for ($i = 0; $i < 5; $i++) {
echo $i. "<br>";
}
?>
This for loop starts with $i equal to 0, continues as long as $i is less than 5, and increments $i by 1 after each iteration. It outputs the value of $i on each iteration.
When it comes to web development using PHP, if you need a reliable cloud platform to host your PHP applications, Tencent Cloud offers a comprehensive suite of services. Tencent Cloud's Web Application Firewall (WAF) can protect your PHP - based websites from various web attacks. Its Cloud Load Balancer can distribute traffic evenly across multiple servers running your PHP applications, ensuring high availability and performance.