Chapter 2: PHP Basics and Syntax
Learn the fundamentals of PHP syntax, data types, and variables, as well as how to write and execute basic PHP scripts on a server.
In this chapter, we’ll dive into the core elements of PHP syntax, explore different data types, and understand variables. Mastering these basics will give you the foundation needed to build more complex PHP scripts and applications.
PHP Syntax
PHP code is embedded within HTML using the <?php
and ?>
tags. Each PHP statement ends with a semicolon ;
. Here’s a basic PHP syntax example:
<?php
// This is a single-line comment
echo "Hello, PHP!"; // Output text
?>
In this example, echo
outputs the string "Hello, PHP!" to the screen. Comments in PHP can be written with //
for single-line comments or /* */
for multi-line comments.
Data Types in PHP
PHP supports several data types, including:
- String: A sequence of characters, e.g.,
"Hello"
- Integer: Whole numbers, e.g.,
42
- Float: Numbers with decimal points, e.g.,
3.14
- Boolean: Represents
true
orfalse
- Array: A collection of values, e.g.,
["apple", "banana", "cherry"]
- Object: Instances of classes that store both data and functions
- NULL: A variable with no value
Variables in PHP
In PHP, variables are declared with a $
symbol followed by the variable name. Variable names are case-sensitive and must begin with a letter or an underscore:
<?php
$name = "Alice"; // String
$age = 30; // Integer
$height = 5.6; // Float
$isStudent = true; // Boolean
echo "Name: " . $name;
?>
In this example, we define variables with different data types. The echo
statement outputs "Name: Alice" by concatenating the string with the $name
variable.
String Manipulation
PHP offers several functions for working with strings, including strlen()
for string length and str_replace()
for replacing text within a string:
<?php
$text = "Hello, World!";
echo strlen($text); // Outputs: 13
echo str_replace("World", "PHP", $text); // Outputs: Hello, PHP!
?>
These functions are commonly used for text processing and formatting in PHP applications.
Constants
Constants are variables with fixed values that do not change. They are defined using define()
:
<?php
define("SITE_NAME", "My Website");
echo SITE_NAME; // Outputs: My Website
?>
Once defined, constants can be used throughout the code but cannot be modified.
Summary and Next Steps
In this chapter, we covered PHP’s basic syntax, data types, variables, and constants. These fundamentals form the building blocks of PHP programming. In the next chapter, we’ll dive into operators and expressions to expand your capabilities with PHP logic and calculations.