In this tutorial, we will explore the basics of PHP coding. We will cover fundamental concepts, syntax, and provide simple examples to help you get started with PHP programming.
<?php
// This is a single-line comment
/*
This is a multi-line comment
*/
// Defining a variable
$greeting = "Hello, World!";
echo $greeting; // Output: Hello, World!
// Function to add two numbers
function add($a, $b) {
return $a + $b;
}
// Using the function
$result = add(5, 10);
echo "The sum is: " . $result; // Output: The sum is: 15
// Conditional statement
if ($result > 10) {
echo "The result is greater than 10.";
} else {
echo "The result is 10 or less.";
}
// Looping through an array
$fruits = array("Apple", "Banana", "Cherry");
foreach ($fruits as $fruit) {
echo $fruit . " ";
}
?>
Let’s break down the code step by step:
- Comments:
- PHP allows you to add comments to your code for better readability. You can use single-line comments (
//
) or multi-line comments (/* ... */
).
- PHP allows you to add comments to your code for better readability. You can use single-line comments (
- Variables:
- Variables in PHP start with a dollar sign (
$
). In our example, we defined a variable$greeting
and assigned it the string “Hello, World!”. Theecho
statement is used to output the value of the variable.
- Variables in PHP start with a dollar sign (
- Functions:
- Functions are reusable blocks of code. We created a function called
add
that takes two parameters,$a
and$b
, and returns their sum. We then called this function with the values 5 and 10, storing the result in the variable$result
.
- Functions are reusable blocks of code. We created a function called
- Conditional Statements:
- PHP supports conditional statements like
if
andelse
. In our example, we checked if$result
is greater than 10 and printed a message accordingly.
- PHP supports conditional statements like
- Loops:
- We used a
foreach
loop to iterate through an array of fruits. This loop allows us to execute a block of code for each element in the array, printing each fruit.
- We used a
By understanding these basic concepts, you can start writing your own PHP scripts. PHP is a powerful language for web development, and mastering its fundamentals will set you on the path to creating dynamic web applications. Happy coding!
I’ve been designing web applications—on and off—since 2001, back when animated GIFs were all the rage and ‘responsive design’ meant answering your client’s emails. Over the past 14 years, I’ve kept pace with the ever-evolving trends in PHP development, successfully delivering a variety of projects that made my clients happy (and kept me caffeinated).
This website serves as my soapbox—a place to share the insights I’ve picked up along the way with anyone curious enough to dive in. Welcome aboard!
Need some custom work done? Or, just want to reach out? Email: dan@danoriordan.com