Contents
Basic Concepts
PHP Syntax
PHP Overview: A Beginner’s Guide to Syntax
PHP is a versatile server-side language widely used in web development. Its straightforward syntax makes it suitable for both beginners and advanced developers. In this guide, we will explore the basic syntax of PHP. PHP scripts can be embedded within HTML using special PHP tags.
Basic PHP Syntax
PHP code is executed between PHP tags. The most commonly used tags are <?php ... ?>
, which mark the beginning and end of PHP code. This is known as Escaping to PHP.
These tags, also known as Canonical PHP tags, indicate to the PHP parser which parts of the document to process. Everything outside these tags is treated as plain HTML. Each PHP command must end with a semicolon (;
).
PHP Syntax Example
Output:
Greetings from PHP!
Embedding PHP in HTML
You can embed PHP code within an HTML document using PHP tags. In this example, the <?php echo "Welcome to PHP!"; ?>
dynamically adds content into the HTML.
PHP Example
Output:
Welcome to PHP!
Short PHP Tags
Short tags allow for a more compact syntax, starting with <?
and ending with ?>
. This feature works only if the short_open_tag
setting in the php.ini
configuration file is enabled.
echo "Short tag in action!";
?>
Output:
Short tag in action!
Case Sensitivity in PHP
PHP is partly case-sensitive:
- Keywords (such as
if
,else
,while
,echo
) are not case-sensitive. - Variables are case-sensitive.
Example:
Output:
Hello, Developer!
Notice: Undefined variable: message
Comments in PHP
Comments help make the code easier to understand and maintain. They are ignored by the PHP engine.
- Single-Line Comments: Single-line comments are brief explanations added with
//
or#
.
Output:
Single-line comment example!
- Multi-Line Comments: Multi-line comments span several lines, beginning with
/*
and ending with*/
.
Output:
Learning PHP!
Variables and Data Types
Variables store data and are defined with the $
symbol followed by the variable name.
Declaring Variables: Variables are created by assigning a value using the assignment operator (=
).
$name = "Alice"; // String
$age = 25; // Integer
$isStudent = false; // Boolean
Data Types in PHP
PHP supports multiple data types:
- String: A sequence of characters.
- Integer: Whole numbers.
- Float: Numbers with decimal points.
- Boolean: True or false values.
- Array: A collection of values.
- Object: An instance of a class.
- NULL: A variable with no value.
- Resource: A reference to external resources like database connections.
Code Blocks in PHP
PHP allows grouping of multiple statements into a block using curly braces ({}
). A block is typically used with conditions or loops.
0) {
echo "Number is positive.\n";
echo "It is greater than zero.";
}
?>
Output:
Number is positive.
It is greater than zero.
PHP Variables
PHP Variables are one of the core concepts in programming. They are used to store information that can be utilized and altered throughout your code. PHP variables are straightforward, dynamically typed (meaning there’s no need to explicitly declare their type), and crucial for building dynamic, interactive web applications.
Declaring Variables in PHP
To define a variable in PHP, simply assign a value to it using the $
symbol followed by the variable name. Variable names are case-sensitive and must start with either a letter or an underscore, followed by any combination of letters, numbers, or underscores.
Example:
Variable Naming Conventions
When working with variables in PHP, it’s important to follow best practices to ensure your code remains clean and readable:
1. Start with a Letter or Underscore: Variable names must begin with either a letter or an underscore, not a number.
2. Use Descriptive Names: Make sure the variable name clearly describes its purpose, e.g., $customerName, $totalPrice.
3. Case Sensitivity: Remember that variable names are case-sensitive in PHP, so $count and $Count are treated as two distinct variables.
4. Avoid Reserved Keywords: Avoid using PHP reserved keywords (e.g., class, function) as variable names.
Example of Valid and Invalid Variable Names:
PHP Data Types
- Integer: Whole numbers, either positive or negative, without decimal points.
- Float: Numbers with decimal points or those in exponential notation.
- NULL: Represents a variable that has no value.
- String: A sequence of characters, enclosed in single or double quotes.
- Boolean: Holds one of two possible values:
true
orfalse
. - Array: A collection of multiple values, stored in a single variable.
- Object: An instance of a class.
- Resource: Special variables holding references to external resources, like database connections.
PHP Variable Scope
Variable scope determines where a variable can be accessed in your code. PHP variables can have local, global, static, or superglobal scope.
1. Local Scope (Local Variables): Variables defined inside a function are local to that function and cannot be accessed outside it. A variable defined outside the function with the same name remains a separate variable.
Example:
Output:
Local variable inside the function: 50
Global variable outside the function: 100
2. Global Scope (Global Variables): Variables declared outside a function have global scope and can be accessed directly outside the function. To access them inside a function, use the global
keyword.
Example:
Output:
Global variable inside the function: 42
Global variable outside the function: 42
3. Static Variables: In PHP, local variables are destroyed after the function finishes execution. If you need a variable to retain its value across multiple function calls, use the static
keyword.
Example:
Output:
Static count: 2
Local temp: 11
Static count: 3
Local temp: 11
4. Superglobals: Superglobals are built-in arrays in PHP, accessible throughout the script (even inside functions). Common examples include $_GET
, $_POST
, $_SESSION
, $_COOKIE
, $_SERVER
, and $_GLOBALS
.
Example:
Output:
Current file: /path/to/current/script.php
Variable Variables
PHP allows dynamic variable names, known as “variable variables.” These are variables whose names are created dynamically by the value of another variable.
Example:
Output:
Paris
PHP echo and print
PHP echo and print are two commonly used language constructs for displaying data on the screen. Since they are language constructs rather than functions, parentheses are not required (though parentheses can be used with print
). Both constructs are frequently employed for printing strings, variables, and HTML content in PHP scripts.
- echo: Generally faster and capable of outputting multiple strings separated by commas.
- print: Slightly slower, returns a value of
1
, and can only take one argument at a time.
PHP echo Statement
The echo
construct is simple to use and doesn’t behave like a function, meaning parentheses are not necessary. However, they can be included if desired. The echo
statement ends with a semicolon (;
). It allows you to display one or more strings, numbers, variables, or results of expressions.
Basic Syntax of echo
Without parentheses:
echo "Hello, World!";
With parentheses (though optional):
echo("Hello, World!");
Displaying Variables with echo
We can use echo
to easily output variables, numbers, and results of expressions.
Example:
Output:
Welcome to PHP!
15 + 25 = 40
In the above code, the dot (.
) operator is used for concatenation, and \n
is used to insert a new line.
Displaying Strings with echo
You can use echo
to print strings directly.
Example:
Output:
PHP is a popular scripting language!
Displaying Multiple Strings with echo
You can pass multiple arguments to the echo
statement, separating them with commas.
Example:
Output:
Hello from PHP!
PHP print Statement
The print
construct is similar to echo
and is often used interchangeably. Like echo
, it does not require parentheses, but can use them optionally. Unlike echo
, print
can only output a single argument and always returns a value of 1
.
Basic Syntax of print
Without parentheses:
print "Learning PHP is fun!";
With parentheses:
print("Learning PHP is fun!");
Output:
x && y: false
x || y: true
Displaying Variables with print
You can display variables with print
in the same way as with echo
.
Example:
Output:
PHP is awesome!
30 + 40 = 70
Displaying Strings with print
You can print strings with print
in a similar way to echo
, but only one string can be printed at a time.
Example:
Output:
PHP makes web development easier!
Difference Between echo and print Statements in PHP
While both echo
and print
are used to display data, there are a few key differences between them:
S.No | echo | |
---|---|---|
1. | Can take multiple arguments separated by commas. | Only accepts one argument. |
2. | Does not return any value. | Always returns a value of 1 . |
3. | Displays multiple strings or values in one statement. | Can only display one string or value. |
4. | Slightly faster than print . | Slightly slower than echo . |
PHP Data Types
PHP data types are an essential concept that defines how variables store and manage data. PHP is a loosely typed language, meaning that variables do not require a specific data type to be declared. PHP supports eight different types of data, which are discussed below.
Predefined Data Types
1. Integer: Integers represent whole numbers, both positive and negative, without any fractional or decimal parts. They can be written in decimal (base 10), octal (base 8), or hexadecimal (base 16). By default, numbers are assumed to be in base 10. Octal numbers are prefixed with 0
and hexadecimal numbers with 0x
. PHP integers must be within the range of -2^31 to 2^31.
Example:
Output:
Sum of integers: 126
int(126)
2. Float (Double): Floats (or doubles) represent numbers with decimal points or in exponential notation. They can handle both positive and negative values. In PHP, float and double are synonymous.
Example:
Output:
Sum of floats: 80.05
float(80.05)
3. String: Strings hold sequences of characters. They can be enclosed within either double quotes ("
) or single quotes ('
). The key difference between them is how PHP handles variable interpolation and escape sequences.
Example:
Output:
The name is John
The name is $name
string(4) "John"
4. Boolean: Booleans are used in conditional statements and can only take two values: TRUE
or FALSE
. In PHP, non-empty values are treated as TRUE
, while 0
, NULL
, and empty strings are considered FALSE
.
Example:
Output:
This statement is true.
User-Defined (Compound) Data Types
1. Array: Arrays in PHP can store multiple values under a single name. These values can be of different data types, making arrays versatile.
Example:
Output:
First fruit: Apple
Second fruit: Banana
Third fruit: Orange
array(3) {
[0]=>
string(5) "Apple"
[1]=>
string(6) "Banana"
[2]=>
string(6) "Orange"
}
2. Objects: Objects are instances of classes. They allow you to create complex data structures that can hold both values and methods for processing data. Objects are explicitly created using the new
keyword.
Example:
model = $model;
}
function displayModel() {
return "Car model: " . $this->model;
}
}
$car = new Car("Toyota");
echo $car->displayModel();
?>
Output:
Car model: Toyota
Special Data Types
1. NULL: The NULL
data type represents a variable that has no value. Variables are automatically assigned NULL
if they have not been initialized or explicitly set to NULL
.
Example:
Output:
Value of the variable is:
NULL
2. Resources: Resources are special variables that hold references to external resources such as database connections or file handles. These are not actual data types in PHP but rather references.
Note: Resource examples typically involve external connections like databases or files, so examples will depend on external setups.
PHP Functions to Check Data Types
PHP provides several functions to verify the data type of a variable:
is_int()
: Checks if a variable is an integer.is_string()
: Checks if a variable is a string.is_array()
: Checks if a variable is an array.is_object()
: Checks if a variable is an object.is_bool()
: Checks if a variable is a boolean.is_null()
: Checks if a variable isNULL
.
Example:
Output:
The variable is an integer.
The variable is a string.
PHP Strings
PHP Strings
Strings are among the most important data types in PHP. They are used to handle and manipulate text data, process user inputs, and create dynamic content. PHP offers a variety of functions and methods for working with strings, making it easy to display and modify text.
A string is essentially a sequence of characters. PHP strings can consist of letters, numbers, symbols, and special characters. They are widely used for input/output handling, dynamic content generation, and more.
Declaring Strings in PHP
Strings in PHP can be declared using four different syntaxes: single quotes, double quotes, heredoc, and nowdoc.
1. Single Quotes: Single quotes in PHP are used to define simple strings. Text within single quotes is treated literally, meaning special characters and variables inside them are not interpreted.
Output:
Hello, Code World!
In this case, the string is printed as is.
However, note how the following example works:
Output:
Learning $language is fun!
In this case, the variable $language
is not processed because single-quoted strings do not recognize variables.
2. Double Quotes: Double-quoted strings, on the other hand, do recognize variables and special characters.
class Test {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i); // Loop variable i
}
int i = 20; // Declare i after the loop
System.out.println(i); // Access new i outside the loop
}
}
Output:
Hello, Code Enthusiasts!
Learning PHP is exciting!
In this example, double quotes allow variable substitution, and the \n
special character is interpreted as a new line.
3. Heredoc Syntax: Heredoc (<<<
) is a way to declare a string in PHP without enclosing it in quotes. It behaves similarly to a double-quoted string, allowing variable interpolation and escape sequences.
Output:
Welcome to the world of coding.
This is the best way to learn PHP!
4. Nowdoc Syntax: Nowdoc syntax is similar to heredoc, but it behaves like a single-quoted string—no variables or escape sequences are processed.
Output:
Welcome to PHP.
Enjoy coding!
Key Built-in PHP String Functions
1. strlen()
Function: This function returns the length of the string.
Output:
17
2. strrev()
Function: This function reverses the string.
Output:
!nuf si gnidoC
3. str_replace()
Function: This function replaces all occurrences of a string within another string.
Output:
Coding is challenging!
4. strpos()
Function: This function searches for a string within another string and returns its starting position.
Output:
9
9
bool(false)
5. trim()
Function: This function removes characters or spaces from both sides of a string.
Output:
Hello World!
6. explode()
Function: This function breaks a string into an array based on a delimiter.
Output:
Array
(
[0] => PHP
[1] => is
[2] => great
[3] => for
[4] => web
[5] => development
)
7. strtolower()
Function: This function converts a string to lowercase.
Output:
hello world!
8. strtoupper()
Function: This function converts a string to uppercase.
Output:
HELLO WORLD!
9. str_word_count()
Function: This function counts the number of words in a string.
Output:
5