PHP Programming Book Chapter
PHP Programming Book Chapter
Objectives:
Understand the basics of PHP and its use in web development.
Learn how to install and set up PHP.
Understand basic syntax and how to embed PHP in HTML.
The following HTML markup contains a PHP statement that will add Hello World! to the output:
<!DOCTYPE html>
<html>
<head>
<title>PHP!</title>
Page 1
PHP Programming
</head>
<body>
<p>Hello world!</p>
</body>
</html>
echo has a void return, whereas print returns an int with a value of 1
Both echo and print are language constructs, not functions. That means
they do not require parentheses around their arguments. For cosmetic
consistency with functions, parentheses can be included. Extensive
examples of the use of echo and print are available elsewhere.
C-style printf and related functions are available as well, as in the following
example:
The header() function can send a raw HTTP header. You can add the
Content-Type header to notify the browser of the content we are sending.
Page 2
PHP Programming
This will produce a plain text document with the following content:
Hello World
echo json_encode($data);
This will produce a document of type application/json with the following content:
{"response":"Hello World"}
Note that the header() function must be called before PHP produces any
output, or the web server will have already sent headers for the
response. So, consider the following code:
// Error: We cannot send any output before the headers
echo "Hello";
When using header(), its output needs to be the first byte that's sent from
the server. For this reason it's important to not have empty lines or spaces
in the beginning of the file before the PHP opening tag <?php. For the same
reason, it is considered best practice (see PSR-2) to omit the PHP closing tag
?> from files that contain only PHP and from blocks of PHP code at the very
end of a file.
View the output buffering section to learn how to 'catch' your content
into a variable to output later, for example, after outputting headers.
Page 3
PHP Programming
php -S <host/ip>:<port>
Example usage
<?php
1. Run the command php -S localhost:8080 from the command line. Do not include
http://
. This will start a web server listening on port 8080 using the current
directory that you are in as the document root.
2. Open the browser and navigate to http://localhost:8080. You should see your "Hello
World" page.
Configuration
To override the default document root (i.e. the current directory), use the -t flag:
E.g. if you have a public/ directory in your project you can serve your project from that
directory using php -S localhost:8080 -t public/.
Logs
CLI is basically the same as PHP from web servers, except some differences in
terms of standard input and output.
Page 4
PHP Programming
Triggering
1. Standard input. Run the php command without any arguments, but pipe PHP code
into it: echo '<?php echo "Hello world!";' | php
2. Filename as argument. Run the php command with the name of a PHP source file as
the first argument: php hello_world.php
3. Code as argument. Use the -r option in the php command, followed by the code to
run. The <?php open tags are not required, as everything in the argument is
considered as PHP code: php -r 'echo "Hello world!";'
4. Interactive shell. Use the -a option in the php command to launch an interactive shell. Then,
type (or paste)
retur
HP code and hit
Output
: $ php -a Interactive mode enabled php > echo "Hello world!"; Hello world!
All functions or controls that produce HTML output in web server PHP can be
used to produce output in the stdout stream (file descriptor 1), and all
actions that produce output in error logs in web server PHP will produce
output in the stderr stream (file descriptor 2).
Example.php
<?php
echo "Stdout 1\
n";
trigger_error("S
tderr 2\n");
print_r("Stdout
3\n");
fwrite(STDERR,
"Stderr 4\n");
?>
Stdout 6
<?php
echo "Stdout 1\n"; trigger_error("Stderr 2\n"); print_r("Stdout 3\n"); fwrite(STDERR, "Stderr 4\n");
throw new RuntimeException("Stderr 5\n");
?>
Stdout 6
Page 5
PHP Programming
STDOUT
Stdout 1
Stdout 3
STDERR
Stderr 4
PHP Notice:Stderr 2
in /Example.php on line 3
PHP Fatal error:Uncaught RuntimeException: Stderr 5 in /Example.php:6
Stack trace:
#0 {main}
thrown in /Example.php on line 6
Input
If the last line of PHP code ends with a semicolon, the closing tag is optional
if there is no code following that final line of code. For example, we can
leave out the closing tag after echo "No error"; in the following
example:
<?php echo "No error"; // no closing tag is needed as long as there
is no code below
However, if there is any other code following your PHP code block, the closing tag
is no longer optional:
<?php echo "This will cause an error if you leave out the closing tag"; ?
>
<html>
<body>
</body>
</html>
Page 6
PHP Programming
We can also leave out the semicolon of the last statement in a PHP code block if
that code block has a closing tag:
<?php echo "I
hope this helps!
:D"; echo "No
error" ?>
echo "Here we
use a
semicolon!";
echo "Here as
well!";
echo "Here we use a semicolon and a closing tag because more code
follows";
?>
<?php
echo "Here we
use a
semicolon!";
echo "Here as
well!";
<?php echo "No error"; // no closing tag is needed as long as there is no code below
echo "Here we use a semicolon and a closing tag because more code
follows";
?>
<?php
echo "Here we
use a
semicolon!";
echo "Here as
well!";
echo "Here we use a semicolon but leave out the closing tag";
Page 7
PHP Programming
Standard Tags
These tags are the standard method to embed PHP code in a file.
<?php
?>
Echo Tags
These tags are available in all PHP versions, and since PHP 5.4 are always
enabled. In previous versions, echo tags could only be enabled in conjunction
with short tags.
<?= "Hello World" ?>
Short Tags
You can disable or enable these tags with the option short_open_tag.
<?
echo "Hello World";
?>
Short tags:
are disallowed in
all major PHP
coding standards
are discouraged
in the official
documentation
are disabled by
default in most
distributions
interfere with inline XML's processing instructions
are not accepted in code submissions by most open source projects
ASP Tags
Page 8
PHP Programming
<%
echo "Hello World";
%>
These are an historic quirk and should never be used. They were removed in PHP
7.0.
Chapter 2: Variables
Variables can be accessed via dynamic variable names. The name of a
variable can be stored in another variable, allowing it to be accessed
dynamically. Such variables are known as variable variables.
To turn a variable into a variable variable, you put an extra $ put in front of your
variable.
$funcName = 'add';
Page 9
PHP Programming
$varPrefix = 'foo';
Using {} is only mandatory when the name of the variable is itself an expression,
like this:
$$$$$$$$DoNotTryThisAtHomeKids = $value;
It's important to note that the excessive usage of variable variables is considered a bad practice
by many developers. Since they're not well-suited for static analysis by modern IDEs, large
codebases with many variable variables (or dynamic method invocations) can quickly become
difficult to maintain
Another reason to always use {} or (), is that PHP5 and PHP7 have a slightly
different way of dealing with dynamic variables, which results in a different
outcome in some cases.
Page 10
PHP Programming
Case 1 : $$foo['bar']['baz']
Case 2 : $foo->$bar['baz']
Case 3 : $foo->$bar['baz']()
Case 4 : Foo::$bar['baz']()
Data Types
There are different data types for different purposes. PHP does not have
explicit type definitions, but the type of a variable is determined by the
type of the value that is assigned, or by the type that it is casted to. This is
a brief overview about the types, for a detailed documentation and
examples, see the PHP types topic.
There are following data types in PHP: null, boolean, integer, float, string, object,
resource and array.
Null
$foo = null;
This invalidates the variable and it's value would be undefined or void if
called. The variable is cleared from memory and deleted by the garbage
collector.
Boolean
Page 11
PHP Programming
$foo = true;
$bar = false;
$foo = true;
if ($foo) {
echo "true";
} else {
echo "false";
}
Integer
Float
Floating point numbers, "doubles" or simply called "floats" are decimal numbers.
$foo = 1.23;
$foo = 10.0;
$bar = -INF;
$bar = NAN;
Array
Page 12
PHP Programming
$bar = ["A", true, 123 => 5]; // Short array syntax, PHP 5.4+
Arrays can also associate a key other than an integer index to a value. In
PHP, all arrays are associative arrays behind the scenes, but when we refer
to an 'associative array' distinctly, we usually mean one that contains one
or more keys that aren't integers.
$array = array();
$array["foo"] = "bar";
$array["baz"] = "quux";
$array[42] = "hello";
echo $array["foo"]; // Outputs "bar" echo $array["bar"]; // Outputs "quux" echo $array[42]; // Outputs "hello"
String
$foo = "bar";
$foo = "bar";
echo $foo[0]; // Prints 'b', the first character of the string in $foo.
Object
$foo = new stdClass(); // create new object of class stdClass, which a predefined, empty class
$foo->bar = "baz";
echo $foo->bar; // Outputs "baz"
// Or we can cast an array to an object:
$quux = (object) ["foo" => "bar"]; echo $quux->foo; // This outputs "bar".
Page 13
PHP Programming
Resource
$fp = fopen('file.ext', 'r'); // fopen() is the function to open a file on disk as a resource.
var_dump($fp); // output: resource(2) of type (stream)
function foo() {
global $bob;
$bob->doSomething();
}
Are you confused? Good. You've just learned why globals are confusing and
considered a bad practice.
If this were a real program, your next bit of fun is to go track down all
instances of $bob and hope you find the right one (this gets worse if $bob is
used everywhere). Worse, if someone else goes and defines $bob (or you
forgot and reused that variable) your code can break (in the above code
example, having the wrong object, or no object at all, would cause a fatal
error).
Since virtually all PHP programs make use of code like include('file.php');
your job maintaining code like this becomes exponentially harder the more
files you add.
Also, this makes the task of testing your applications very difficult. Suppose you
use a global variable to hold your database connection:
Page 14
PHP Programming
Function doSomething(){
Global $dbConnector;
$dbConnector->excute(“…”)
in order to unit test this function, you have to override the global
$dbConnector variable, run the tests and then reset it to its original
value, which is very bug prone:
/**
* @test
*/
function testSomething() {
global $dbConnector;
assertTrue(foo());
$bob->doSomething();
Version = 4.1
Page 15
PHP Programming
Superglobal variables
Super globals in PHP are predefined variables, which are always available,
can be accessed from any scope throughout the script.
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
<?php
return $default;
}
// retrieves $_POST['username']
echo getPostValue('username');
Page 16
PHP Programming
class SomeClass {
SomeClass::$counter += 1;
Functions can also define static variables inside their own scope. These
static variables persist through multiple function calls, unlike regular
variables defined in a function scope. This can be a very easy and simple
way to implement the Singleton design pattern:
class Singleton {
static $instance;
// Second call to this function will not get into the if-
statement,
class SomeClass {
public static int $counter = 0;
}
Page 17
PHP Programming
if (!$instance) {
return $instance;
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();
Within the scope of a function or class method, the global keyword may be
used to create an access user-defined global variables.
<?php
$amount_of_log_calls = 0;
function log_message($message) {
Page 18
PHP Programming
global $amount_of_log_calls;
$amount_of_log_calls += 1;
echo $message;
echo $amount_of_log_calls; // 0
log_message("Fir
st log
message!"); echo
$amount_of_log_c
alls; // 1
log_message("Sec
ond log
message!"); echo
$amount_of_log_c
alls; // 2
<?php
$amount_of_log_calls = 0;
function log_message($message) {
global $amount_of_log_calls;
$amount_of_log_calls += 1;
echo $message;
Page 19
PHP Programming
echo $amount_of_log_calls; // 0
log_message("Fir
st log
message!"); echo
$amount_of_log_c
alls; // 1
log_message("Sec
ond log
message!"); echo
$amount_of_log_c
alls; // 2
A second way to access variables from the global scope is to use the special PHP-
defined $GLOBALS array.
The $GLOBALS array is an associative array with the name of the global
variable being the key and the contents of that variable being the value of
the array element. Notice how $GLOBALS exists in any scope, this is
because
$GLOBALS is a superglobal.
// is a superglobal variable.
$GLOBALS['amount_of_log_calls'] += 1;
echo $messsage;
One might ask, why use the $GLOBALS array when the global keyword can also be used to get
a global variable's value? The main reason is using the global keyword will bring the variable
into scope. You then can't reuse the same variable name in the local scope
Superglobals are built-in variables that are always available in all scopes.
Page 20
PHP Programming
Introduction
Put simply, these are variables that are available in all scope in your scripts.
What's a superglobal??
As of PHP version 7.1.3 there are 9 superglobal variables. They are as follows:
Code
$myGlobal = "global"; // declare variable outside of scope
Page 21
PHP Programming
function test()
var_dump($myLocal);
var_dump($GLOBALS["myGlobal"]);
var_dump($myLocal
);
var_dump($myGlob
al);
Output
In the above example $myLocal is not displayed the second time because it
is declared inside the test() function and then destroyed after the function
is closed.
Becoming global
To remedy this there are two options:
Option one:
global
keyword
function test()
global $myLocal;
$myLocal =
"local";
var_dump($my
Local);
var_dump($GLO
Page 22
PHP Programming
BALS["myGlob
al"]);
Note that you cannot assign a value to a variable in the same statement as
the global keyword. Hence, why I had to assign a value underneath. (It is
possible if you remove new lines and spaces but I don't think it is neat.
global
$myLocal; $myLocal = "local").
$GLOBALS["myLocal"] = "local";
$myLocal =
$GLOBALS["my
Local"];
var_dump($my
Local);
var_dump($GLO
BALS["myGlob
al"]);
array (size=36)
Page 23
PHP Programming
'HTTP_CACHE_CONTROL' =>
string 'max-age=0' (length=9)
'HTTP_UPGRADE_INSECURE_REQU
ESTS' => string '1' (length=1)
;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;E:\Program Files\ATI
Technologies\ATI.ACE\Core- Static;E:\Program Files\AMD\ATI.ACE\Core-
Static;C:\Program Files (x86)\AMD\ATI.ACE\Core- Static;C:\Program Files
(x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files\Intel\
Intel(R) Managemen'... (length=1169)
'SERVER_ADDR' =>
string '::1'
(length=3)
'SERVER_PORT' =>
string '80' (length=2)
'REMOTE_ADDR' =>
string '::1'
(length=3)
Page 24
PHP Programming
'GATEWAY_INTERFACE'
=> string 'CGI/1.1'
(length=7)
'SERVER_PROTOCOL' =>
string 'HTTP/1.1'
(length=8)
'REQUEST_METHOD' =>
string 'GET' (length=3)
'QUERY_STRING' =>
string '' (length=0)
'REQUEST_URI' =>
string '/test.php'
(length=13)
'SCRIPT_NAME' =>
string '/test.php'
(length=13) 'PHP_SELF'
=> string '/test.php'
(length=13)
'REQUEST_TIME_FLOAT'
=> float
1491068771.413
'REQUEST_TIME' => int
1491068771
There is a lot to take in there so I will pick out some important ones below.
If you wish to read about them all then consult the indices section of the
documentation.
I might add them all below one day. Or someone can edit and add a good explanation of them
below? Hint, hint;)
http://www.example.com/index.php
Page 25
PHP Programming
$_GET
An associative array of variables passed to the current script via
the URL parameters.
$_GET is an array that contains all the URL parameters; these are
the whatever is after the ? in the URL.
Using http://www.example.com/index.php?myVar=myVal as an
example. This information from this URL can be obtained by
accessing in this format $_GET["myVar"] and the result of
this will be myVal.
Security risk
It is very important not to send any sensitive information via
the URL as it will stay in history of the computer and will be
visible to anyone that can access that browser.
Page 26
PHP Programming
$_POST
Security risk
Sending data via POST is also not secure. Using HTTPS will ensure
that data is kept more secure.
$_FILES
Cookie
Page 27
PHP Programming
In PHP, a cookie is a small piece of data sent from a web server and stored on the client’s
browser. Cookies are often used to track users, store preferences, and manage sessions. Here's
a detailed breakdown of cookies in PHP:
1. Setting a Cookie
The setcookie() function is used to define a cookie in PHP. It sends an HTTP header to
the browser to store a cookie, which will then be sent back to the server with each subsequent
request to the same domain.
setcookie(
"name", // Cookie name
"value", // Cookie value
time() + 3600, // Expiration (1 hour from now)
"/", // Path ("/" means accessible across the entire domain)
"example.com", // Domain (if omitted, the cookie is only accessible on the current
domain)
true, // Secure flag (true = only send over HTTPS)
true // HttpOnly flag (true = not accessible by JavaScript)
);
Parameters of setcookie()
1. name (string): The name of the cookie, which will be used to access it later via
$_COOKIE.
2. value (string): The value stored in the cookie (can be any string, often encoded to
handle complex data).
3. expire (int): A timestamp that determines when the cookie expires. Use time() +
seconds to set it for a specific time in the future.
4. path (string): Specifies the path on the server where the cookie is available. "/"
means the cookie is available across the entire domain.
5. domain (string): Specifies the domain associated with the cookie, allowing it to be
shared across subdomains if specified (e.g., ".example.com").
6. secure (bool): When true, the cookie is only sent over secure HTTPS connections.
7. httponly (bool): When true, the cookie is only accessible via HTTP(S) and not
JavaScript. This enhances security against XSS (Cross-Site Scripting) attacks.
2. Retrieving a Cookie
Cookies set by setcookie() can be accessed using the $_COOKIE superglobal array in
PHP.
Page 28
PHP Programming
if (isset($_COOKIE['name'])) {
echo "Cookie value: " . $_COOKIE['name'];
} else {
echo "Cookie not set!";
}
3. Modifying a Cookie
To change a cookie’s value or expiration, you must use setcookie() again with the same
cookie name and updated values.
4. Deleting a Cookie
To delete a cookie, set its expiration date to a time in the past. This tells the browser to
immediately discard the cookie.
Important Notes
Headers Must Be Sent Before Output: Cookies are set via HTTP headers, so
setcookie() must be called before any HTML or other output.
Security Considerations:
o Always use the HttpOnly and Secure flags for sensitive information to
prevent JavaScript access and enforce secure transmission.
o For sensitive applications, avoid storing personally identifiable information
(PII) in cookies directly.
Session Management: Track user sessions, e.g., to keep users logged in.
User Preferences: Store user preferences for personalizing their experience.
Analytics and Tracking: Track user behavior for analytical purposes.
Cookies play a critical role in PHP applications for maintaining state, which is especially
important given that HTTP is stateless.
In PHP, sessions are a way to store data across multiple pages for a user. Unlike cookies,
session data is stored on the server, and only a session ID is stored on the client side. This
makes sessions more secure for handling sensitive information.
Page 29
PHP Programming
1. Starting a Session
To use sessions, you first need to start a session on each page where you want to access
session data. This is done with the session_start() function, which must be called
before any HTML output.
<?php
session_start(); // Start a new session or resume the existing one
?>
Session variables can be set by assigning values to the $_SESSION superglobal array.
<?php
session_start();
$_SESSION["username"] = "JohnDoe"; // Store username in session
$_SESSION["email"] = "johndoe@example.com"; // Store email in session
?>
You can retrieve session data on any page after calling session_start().
<?php
session_start();
echo "Username: " . $_SESSION["username"];
echo "Email: " . $_SESSION["email"];
?>
<?php
session_start();
$_SESSION["username"] = "JaneDoe"; // Update session variable
?>
Page 30
PHP Programming
To remove specific session variables, use unset() with the desired key.
<?php
session_start();
unset($_SESSION["username"]); // Remove only the username from the session
6. Destroying a Session
To completely end a session, use session_destroy(). This removes all session data, but
you must first call session_start() to access the session.
<?php
session_start();
session_unset(); // Free all session variables
session_destroy(); // Destroy the session
?>
Here’s a simple example of how sessions can be used for user login.
login.php
<?php
session_start();
Page 31
PHP Programming
In this example:
1. Login: Validates user credentials and sets session data for logged-in users.
2. Dashboard: Checks if a session variable exists before granting access to the protected
content.
In PHP, there are several ways to output the value of a variable. Here are some commonly
used methods:
Page 32
PHP Programming
1. Using echo
<?php
$name = "Alice";
echo $name; // Outputs: Alice
?>
2. Using print
Similar to echo, print can be used to output variables. It always returns 1, so it's often used
in expressions.
<?php
$name = "Alice";
print $name; // Outputs: Alice
?>
3. Using print_r
print_r is used to print complex data types like arrays or objects in a readable format. It
doesn’t add formatting but is helpful for debugging.
<?php
$array = array("Alice", "Bob", "Charlie");
print_r($array);
// Outputs: Array ( [0] => Alice [1] => Bob [2] => Charlie )
?>
4. Using var_dump
var_dump provides detailed information about a variable, including its type and length. This
is particularly useful for debugging.
<?php
$number = 42;
var_dump($number);
// Outputs: int(42)
Page 33
PHP Programming
var_dump($names);
// Outputs: array(2) { [0]=> string(5) "Alice" [1]=> string(3) "Bob" }
?>
5. Using printf
printf allows formatted output, making it possible to define the way the output is displayed.
<?php
$number = 42;
printf("The number is %d", $number); // Outputs: The number is 42
?>
6. Using sprintf
sprintf works similarly to printf, but instead of printing the result directly, it returns it as a
string, which can then be stored or used elsewhere.
<?php
$number = 42;
$output = sprintf("The number is %d", $number);
echo $output; // Outputs: The number is 42
?>
Chapter 6: Constants
In PHP, a constant is a name or an identifier for a simple value that does not change during
the execution of a script. Once defined, constants cannot be altered or redefined. Constants
Page 34
PHP Programming
are often used to define values that are required to stay the same throughout the application,
such as configuration values.
Defining a Constant
You define a constant in PHP using the define() function. Constant names are usually written
in uppercase to distinguish them from variables.
<?php
define("SITE_NAME", "MyWebsite");
define("PI", 3.14159);
?>
Accessing Constants
<?php
echo SITE_NAME; // Outputs: MyWebsite
echo PI; // Outputs: 3.14159
?>
Characteristics of Constants
1. Global Scope: Constants are automatically global and can be accessed from any part
of the script, regardless of scope.
2. Immutable: Once defined, constants cannot be redefined or changed.
3. Case-Sensitivity: By default, constant names are case-sensitive. To define a case-
insensitive constant, use the third parameter in define() (although this feature was
deprecated in PHP 7.3).
Page 35
PHP Programming
PHP also allows you to define constants using the const keyword, but only at the top level,
not inside functions or control structures. Unlike define(), const constants are always case-
sensitive.
<?php
const APP_VERSION = "1.0.0";
echo APP_VERSION; // Outputs: 1.0.0
?>
Starting with PHP 5.6, you can define arrays as constants using the const keyword (but not
with define()).
<?php
const COLORS = ["red", "green", "blue"];
echo COLORS[1]; // Outputs: green
?>
Magic Constants
PHP provides several predefined constants, called magic constants, that change depending on
where they are used. They start and end with double underscores.
php
Copy code
<?php
echo "This is line " . __LINE__; // Outputs the line number
echo "File path: " . __FILE__; // Outputs the full path of the file
?>
Summary
Page 36
PHP Programming
Magic constants in PHP are predefined constants that change based on where they are used.
They provide useful information about the file, line number, function, class, or namespace in
which they are used. Each magic constant starts and ends with double underscores (__),
which distinguishes them from regular constants.
1. __LINE__
php
Copy code
<?php
echo "This is line number " . __LINE__; // Outputs the line number, e.g., "This is line
number 3"
?>
2. __FILE__
Returns the full path and filename of the file where it is used.
php
Copy code
<?php
echo "The full path of this file is " . __FILE__; // Outputs the file path
?>
3. __DIR__
Returns the directory of the file where it is used, without the file name.
It’s useful for including files with relative paths.
php
Copy code
<?php
echo "The directory of this file is " . __DIR__; // Outputs the directory path
?>
4. __FUNCTION__
php
Copy code
Page 37
PHP Programming
<?php
function myFunction() {
echo "The function name is " . __FUNCTION__;
}
myFunction(); // Outputs: The function name is myFunction
?>
5. __CLASS__
php
Copy code
<?php
class MyClass {
public function showClassName() {
echo "The class name is " . __CLASS__;
}
}
$obj = new MyClass();
$obj->showClassName(); // Outputs: The class name is MyClass
?>
6. __TRAIT__
php
Copy code
<?php
trait MyTrait {
public function getTraitName() {
echo "The trait name is " . __TRAIT__;
}
}
class MyClass {
use MyTrait;
}
$obj = new MyClass();
$obj->getTraitName(); // Outputs: The trait name is MyTrait
?>
7. __METHOD__
Returns the class method name in which it is called, including the class name if it’s
within a class.
php
Copy code
Page 38
PHP Programming
<?php
class MyClass {
public function showMethodName() {
echo "The method name is " . __METHOD__;
}
}
$obj = new MyClass();
$obj->showMethodName(); // Outputs: The method name is MyClass::showMethodName
?>
8. __NAMESPACE__
php
Copy code
<?php
namespace MyNamespace;
echo "The namespace is " . __NAMESPACE__; // Outputs: The namespace is MyNamespace
?>
Summary of Magic Constants
Magic Constant Description
Debugging: Show file paths, line numbers, and class or function names for
troubleshooting.
File Inclusion: Use __DIR__ for relative file paths.
Logging: Log error locations by using __FILE__ and __LINE__.
Chapter 8: Comments
Page 39
PHP Programming
In PHP, comments are used to annotate the code to explain what it does, making it easier for
others (or your future self) to understand. Comments are ignored by the PHP interpreter, so
they don’t affect the execution of the code. PHP supports three types of comments: single-
line comments, multi-line comments, and PHPDoc comments.
1. Single-Line Comments
Single-line comments are useful for brief explanations or notes about a specific line of code.
They can be added using // or #.
Using //
php
Copy code
<?php
echo "Hello, World!"; // This is a single-line comment
Using #
php
Copy code
<?php
echo "Hello, PHP!"; # Another way to add a single-line comment
2. Multi-Line Comments
Multi-line comments are useful for longer descriptions or explanations that span multiple
lines. These are written between /* and */.
php
Copy code
<?php
/*
This is a multi-line comment.
It can span multiple lines.
It is useful for larger explanations or commenting out blocks of code.
*/
echo "Hello, Multiline Comment!";
?>
3. PHPDoc Comments
PHPDoc comments are a specific type of multi-line comment used to document functions,
classes, and methods. They are written between /** and */ and follow a specific structure that
can be parsed by documentation generators.
php
Copy code
<?php
/**
* Adds two numbers together.
*
Page 40
PHP Programming
Use Cases
Using comments effectively improves code readability and maintainability, making it easier
for others to work with your code.
Chapter 9: Types
PHP has a variety of data types used to represent different kinds of values. These types can be
classified into several categories: scalar types, compound types, and special types. Each type
is designed for a specific kind of data or task.
1. Scalar Types
These are the basic data types that represent a single value.
a. Integer
php
Copy code
<?php
$age = 25;
echo $age; // Outputs: 25
Page 41
PHP Programming
?>
b. Float (Double)
php
Copy code
<?php
$price = 19.99;
echo $price; // Outputs: 19.99
?>
c. String
Represents a sequence of characters enclosed in single quotes (') or double quotes (").
Example: "Hello, World!"
php
Copy code
<?php
$name = "Alice";
echo $name; // Outputs: Alice
?>
d. Boolean
php
Copy code
<?php
$is_active = true;
$is_admin = false;
?>
2. Compound Types
a. Array
php
Copy code
<?php
$fruits = array("Apple", "Banana", "Orange");
$person = array("name" => "John", "age" => 30);
Page 42
PHP Programming
php
Copy code
<?php
class Car {
public $brand;
public function drive() {
echo "Driving...";
}
}
a. NULL
php
Copy code
<?php
$nothing = NULL;
echo $nothing; // Outputs nothing
?>
b. Resource
php
Copy code
<?php
$file = fopen("example.txt", "r");
echo gettype($file); // Outputs: resource
?>
Page 43
PHP Programming
4. Pseudo-Types
These are not actual data types in the strict sense but are used in PHP documentation and
functions.
a. Mixed
b. Callable
php
Copy code
<?php
function myFunction() {
echo "Called!";
}
$callable = 'myFunction';
if (is_callable($callable)) {
$callable(); // Outputs: Called!
}
?>
Type Juggling (Implicit Type Conversion)
In PHP, types are often automatically converted depending on the context. This process is
called type juggling.
php
Copy code
<?php
$number = "5" + 10; // PHP converts the string "5" to the integer 5, result is 15
echo $number; // Outputs: 15
?>
Type Casting (Explicit Type Conversion)
You can also force a variable to be a specific type by using type casting.
php
Copy code
<?php
$number = "5.67";
$int_number = (int) $number; // Casts the string to an integer
echo $int_number; // Outputs: 5
?>
Page 44
PHP Programming
Type Declarations
In PHP 7+, you can declare the type of parameters, return values, and class properties.
Understanding these types and how to work with them is crucial to effective PHP
programming.
PHP provides a wide variety of operators to perform operations on variables and values.
These operators can be grouped into different categories: arithmetic, assignment, comparison,
logical, bitwise, and others. Each type serves a specific purpose in handling data within a
PHP script.
1. Arithmetic Operators
Page 45
PHP Programming
Example:
php
Copy code
<?php
$a = 10;
$b = 2;
echo $a + $b; // Outputs: 12
echo $a - $b; // Outputs: 8
echo $a * $b; // Outputs: 20
echo $a / $b; // Outputs: 5
echo $a % $b; // Outputs: 0
echo $a ** $b; // Outputs: 100 (10 raised to the power of 2)
?>
2. Assignment Operators
Example:
php
Copy code
<?php
$a = 5;
$a += 2; // $a is now 7
$a *= 3; // $a is now 21
?>
Page 46
PHP Programming
3. Comparison Operators
=== Identical Returns true if both values and types are equal $a === $b
!== Not identical Returns true if values or types are not equal $a !== $b
> Greater than Returns true if left is greater than right $a > $b
< Less than Returns true if left is less than right $a < $b
>= Greater or equal Returns true if left is greater than or equal $a >= $b
<= Less or equal Returns true if left is less than or equal $a <= $b
Example:
php
Copy code
<?php
$a = 10;
$b = 5;
echo $a > $b; // Outputs: 1 (true)
echo $a == $b; // Outputs: (false)
?>
4. Logical Operators
` ` Or
And (low
and Same as && but with lower precedence $a and $b
precedence)
Page 47
PHP Programming
Example:
php
Copy code
<?php
$a = true;
$b = false;
echo $a && $b; // Outputs: (false)
echo $a || $b; // Outputs: 1 (true)
?>
5. Increment/Decrement Operators
Example:
php
Copy code
<?php
$a = 5;
echo ++$a; // Outputs: 6 (increments before output)
echo $a++; // Outputs: 6 (outputs first, then increments)
?>
6. String Operators
Example:
php
Copy code
<?php
$a = "Hello, ";
$b = "World!";
echo $a . $b; // Outputs: Hello, World!
$a .= $b;
echo $a; // Outputs: Hello, World!
?>
Page 48
PHP Programming
7. Array Operators
Example:
php
Copy code
<?php
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "apple", "b" => "banana", "c" => "cherry");
$c = $a + $b; // Union of $a and $b
print_r($c); // Outputs: Array ( [a] => apple [b] => banana [c] =>
cherry )
?>
8. Bitwise Operators
` ` Or Bitwise OR
In PHP, references provide a way to create an alias for a variable. When a variable is
assigned by reference, any changes made to the reference will affect the original variable, and
vice versa. This is particularly useful when you want to manipulate data without copying it,
which can be more memory-efficient.
Creating References
You can create a reference by using the & operator when assigning a variable.
Page 49
PHP Programming
Example:
php
Copy code
<?php
$a = 10; // $a is assigned the value 10
$b = &$a; // $b is now a reference to $a
1. Mutual Changes: Any changes made to a referenced variable will be reflected in the
original variable.
2. References in Functions: You can also pass variables by reference to functions,
allowing the function to modify the original variable.
$num = 5;
increment($num);
echo $num; // Outputs: 6
?>
3. References with Arrays: You can also create references with arrays.
Example:
php
Copy code
<?php
$array1 = array(1, 2, 3);
$array2 = &$array1; // $array2 is a reference to $array1
Example:
php
Copy code
Page 50
PHP Programming
<?php
$a = 100;
$b = $a; // $b is a copy of $a
$b = 200; // This does not affect $a
echo $a; // Outputs: 100
$c = &$a; // $c is a reference to $a
$c = 300; // This affects $a
echo $a; // Outputs: 300
?>
5. Unset References: When you unset a reference, only the reference itself is removed,
not the original variable.
Example:
php
Copy code
<?php
$a = 5;
$b = &$a; // $b is a reference to $a
unset($b); // Only $b is unset
6. References and Functions Return: Functions can return references using the &
operator.
Example:
php
Copy code
<?php
function &getArray() {
static $arr = array(1, 2, 3);
return $arr; // Returning a reference
}
$arrayRef = &getArray();
$arrayRef[0] = 10;
print_r(getArray()); // Outputs: Array ( [0] => 10 [1] => 2 [2] => 3 )
?>
Limitations of References
Page 51
PHP Programming
Summary
References in PHP allow you to create aliases for variables, enabling you to manipulate the
original variable through its reference. They can enhance performance by avoiding
unnecessary copies of data and are particularly useful in function arguments and return
values. However, care should be taken to understand the implications of using references, as
they can lead to unintended side effects if not managed properly.
Arrays in PHP are powerful data structures that can store multiple values in a single variable.
They can hold values of different types and are categorized mainly into two types: indexed
arrays and associative arrays. PHP also supports multi-dimensional arrays, which can store
arrays within arrays.
1. Indexed Arrays
Indexed arrays use numeric indexes, starting from 0 by default, to access their elements.
Example:
php
Copy code
<?php
$fruits = array("Apple", "Banana", "Cherry"); // Using the array() constructor
$colors = ["Red", "Green", "Blue"]; // Using short array syntax (PHP 5.4+)
Associative arrays use named keys (strings) to access their elements instead of numeric
indexes.
Example:
php
Copy code
<?php
$person = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
Page 52
PHP Programming
3. Multi-Dimensional Arrays
Multi-dimensional arrays are arrays that contain other arrays as their elements. They can be
thought of as arrays of arrays.
Example:
php
Copy code
<?php
$students = array(
array("name" => "Alice", "age" => 21),
array("name" => "Bob", "age" => 22),
array("name" => "Charlie", "age" => 23)
);
a. Creating Arrays
b. Adding Elements
Example:
php
Copy code
<?php
$numbers = array(1, 2, 3);
array_push($numbers, 4, 5); // Adds 4 and 5 to the end of the array
$numbers[] = 6; // Appends 6
print_r($numbers); // Outputs: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
?>
c. Removing Elements
Example:
php
Page 53
PHP Programming
Copy code
<?php
$colors = array("Red", "Green", "Blue");
array_pop($colors); // Removes Blue
unset($colors[0]); // Removes Red
print_r($colors); // Outputs: Array ( [1] => Green )
?>
d. Counting Elements
php
Copy code
<?php
$fruits = array("Apple", "Banana", "Cherry");
echo count($fruits); // Outputs: 3
?>
e. Sorting Arrays
Example:
php
Copy code
<?php
$numbers = array(3, 1, 4, 2);
sort($numbers); // Sorts the array
print_r($numbers); // Outputs: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
?>
f. Merging Arrays
php
Copy code
<?php
$array1 = array("a" => "red", "b" => "green");
$array2 = array("c" => "blue", "d" => "yellow");
$merged = array_merge($array1, $array2);
print_r($merged); // Outputs: Array ( [a] => red [b] => green [c] => blue [d] => yellow )
?>
g. Searching Arrays
Page 54
PHP Programming
array_search(): Searches for a value in an array and returns the corresponding key.
php
Copy code
<?php
$fruits = array("Apple", "Banana", "Cherry");
echo in_array("Banana", $fruits) ? "Found" : "Not found"; // Outputs: Found
?>
Iterating Over Arrays
a. foreach Loop
php
Copy code
<?php
$fruits = array("Apple", "Banana", "Cherry");
foreach ($fruits as $fruit) {
echo $fruit . " ";
} // Outputs: Apple Banana Cherry
?>
b. for Loop
You can also use a for loop if you need the index.
php
Copy code
<?php
$numbers = array(1, 2, 3, 4);
for ($i = 0; $i < count($numbers); $i++) {
echo $numbers[$i] . " ";
} // Outputs: 1 2 3 4
?>
Conclusion
Arrays in PHP are versatile and essential for managing collections of data. They allow you to
group related values together, making it easier to manipulate and retrieve data. Understanding
how to use arrays and the various functions available will significantly enhance your PHP
programming capabilities.
Page 55
PHP Programming
In PHP, there are several ways to iterate over arrays. The choice of method depends on your
specific needs, such as whether you need the keys, values, or both. Here’s a detailed
overview of the different methods for iterating over arrays in PHP:
1. foreach Loop
The foreach loop is the most commonly used method for iterating over arrays. It is simple
and convenient for both indexed and associative arrays.
Syntax:
php
Copy code
foreach ($array as $value) {
// Code to execute
}
Example:
php
Copy code
<?php
$fruits = array("Apple", "Banana", "Cherry");
You can also access the keys while iterating over an associative array.
Syntax:
php
Copy code
foreach ($array as $key => $value) {
// Code to execute
}
Example:
php
Copy code
<?php
$person = array("name" => "John", "age" => 30, "city" => "New York");
Page 56
PHP Programming
// age: 30
// city: New York
?>
2. for Loop
A for loop can be used when you need to work with the array indices.
Syntax:
php
Copy code
for ($i = 0; $i < count($array); $i++) {
// Code to execute
}
Example:
php
Copy code
<?php
$numbers = array(1, 2, 3, 4);
You can also use a while loop with an array pointer to iterate through the elements.
Syntax:
php
Copy code
while (list($key, $value) = each($array)) {
// Code to execute
}
Example:
php
Copy code
<?php
$colors = array("Red", "Green", "Blue");
Page 57
PHP Programming
// 2: Blue
?>
4. do...while Loop
A do...while loop can also be used to iterate over arrays, similar to the while loop.
Example:
php
Copy code
<?php
$animals = array("Dog", "Cat", "Elephant");
$i = 0;
do {
echo $animals[$i] . " ";
$i++;
} while ($i < count($animals));
// Outputs: Dog Cat Elephant
?>
5. array_map()
array_map() applies a callback function to each element of the array and returns an array
containing the results.
Syntax:
php
Copy code
array_map(callback, array1, array2, ...);
Example:
php
Copy code
<?php
$numbers = array(1, 2, 3);
$squared = array_map(function($num) {
return $num ** 2;
}, $numbers);
array_walk() applies a user-defined function to each element of an array, passing the key and
value to the function.
Syntax:
php
Copy code
Page 58
PHP Programming
array_walk($array, callback);
Example:
php
Copy code
<?php
$fruits = array("Apple", "Banana", "Cherry");
Syntax:
php
Copy code
array_reduce($array, callback, initial);
Example:
php
Copy code
<?php
$numbers = array(1, 2, 3, 4);
$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0);
PHP provides various ways to iterate over arrays, each with its own use cases and
advantages. The foreach loop is generally the most straightforward and versatile method for
traversing arrays, while functions like array_map(), array_walk(), and array_reduce() offer
powerful functional programming paradigms for manipulating and processing data in arrays.
Depending on your specific needs and the structure of your data, you can choose the method
that best fits your requirements.
Page 59
PHP Programming
In PHP, you can execute various operations on arrays using built-in functions and control
structures. Below are some common operations you can perform on arrays, along with
examples for clarity:
1. Creating an Array
You can create an array using the array() function or the short array syntax [].
Example:
php
Copy code
<?php
$fruits = array("Apple", "Banana", "Cherry"); // Using array() function
$colors = ["Red", "Green", "Blue"]; // Using short array syntax
print_r($fruits);
print_r($colors);
?>
2. Adding Elements to an Array
a. Using array_push()
php
Copy code
<?php
$fruits = ["Apple", "Banana"];
array_push($fruits, "Cherry", "Date"); // Adds Cherry and Date
print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana [2] => Cherry [3] => Date )
?>
b. Using the [] Operator
php
Copy code
<?php
$fruits[] = "Elderberry"; // Appends Elderberry to the end
print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana [2] => Cherry [3] => Date
[4] => Elderberry )
?>
3. Removing Elements from an Array
You can remove elements using functions like array_pop(), array_shift(), or unset().
a. Using array_pop()
php
Copy code
<?php
$fruits = ["Apple", "Banana", "Cherry"];
Page 60
PHP Programming
You can iterate over an array using loops like foreach, for, or functions like array_map().
Using foreach
php
Copy code
<?php
$fruits = ["Apple", "Banana", "Cherry"];
You can sort an array using functions like sort(), asort(), or ksort().
Page 61
PHP Programming
Using sort()
php
Copy code
<?php
$numbers = [3, 1, 4, 2];
sort($numbers); // Sorts in ascending order
print_r($numbers); // Outputs: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
?>
6. Searching an Array
You can search for values in an array using functions like in_array() and array_search().
Using in_array()
php
Copy code
<?php
$fruits = ["Apple", "Banana", "Cherry"];
if (in_array("Banana", $fruits)) {
echo "Banana is in the array.";
}
// Outputs: Banana is in the array.
?>
Using array_search()
php
Copy code
<?php
$fruits = ["Apple", "Banana", "Cherry"];
$key = array_search("Cherry", $fruits);
echo "Cherry is found at index: $key"; // Outputs: Cherry is found at index: 2
?>
7. Merging Arrays
Example:
php
Copy code
<?php
$array1 = ["a" => "red", "b" => "green"];
$array2 = ["c" => "blue", "d" => "yellow"];
$merged = array_merge($array1, $array2);
print_r($merged); // Outputs: Array ( [a] => red [b] => green [c] => blue [d] => yellow )
?>
8. Filtering Arrays
Page 62
PHP Programming
Example:
php
Copy code
<?php
$numbers = [1, 2, 3, 4, 5];
$evens = array_filter($numbers, function($num) {
return $num % 2 == 0;
});
print_r($evens); // Outputs: Array ( [1] => 2 [3] => 4 )
?>
9. Reducing an Array
Example:
php
Copy code
<?php
$numbers = [1, 2, 3, 4];
$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0);
echo "Sum: $sum"; // Outputs: Sum: 10
?>
Summary
PHP provides a wide range of built-in functions and methods to execute operations on arrays,
making it easy to manipulate and process data. Whether adding, removing, iterating, sorting,
or searching through arrays, PHP offers a flexible and powerful array handling system that is
essential for effective programming.
1. Creating Arrays
You can create arrays using the array() function or the short array syntax [].
Example:
php
Copy code
<?php
Page 63
PHP Programming
print_r($fruits);
print_r($person);
?>
2. Adding Elements to an Array
a. Using array_push()
php
Copy code
<?php
$fruits = ["Apple", "Banana"];
array_push($fruits, "Cherry", "Date");
print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana [2] => Cherry [3] => Date )
?>
b. Using the [] Operator
php
Copy code
<?php
$fruits[] = "Elderberry"; // Appends Elderberry
print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana [2] => Cherry [3] => Date
[4] => Elderberry )
?>
c. Using the array_unshift()
php
Copy code
<?php
array_unshift($fruits, "Apricot"); // Adds Apricot at the beginning
print_r($fruits); // Outputs: Array ( [0] => Apricot [1] => Apple [2] => Banana [3] => Cherry
[4] => Date [5] => Elderberry )
?>
Page 64
PHP Programming
a. Using array_pop()
php
Copy code
<?php
$fruits = ["Apple", "Banana", "Cherry"];
array_pop($fruits); // Removes Cherry
print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana )
?>
b. Using array_shift()
php
Copy code
<?php
array_shift($fruits); // Removes Apple
print_r($fruits); // Outputs: Array ( [0] => Banana )
?>
c. Using unset()
php
Copy code
<?php
$fruits = ["Apple", "Banana", "Cherry"];
unset($fruits[1]); // Removes Banana
print_r($fruits); // Outputs: Array ( [0] => Apple [2] => Cherry )
?>
4. Modifying Elements in an Array
You can directly access an array element by its index or key and assign a new value.
Example:
php
Copy code
<?php
$fruits = ["Apple", "Banana", "Cherry"];
$fruits[1] = "Blueberry"; // Modifies Banana to Blueberry
print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Blueberry [2] => Cherry )
?>
Page 65
PHP Programming
5. Sorting Arrays
a. Using sort()
php
Copy code
<?php
$numbers = [3, 1, 4, 2];
sort($numbers); // Sorts the array
print_r($numbers); // Outputs: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
?>
b. Using asort()
php
Copy code
<?php
$ages = ["John" => 25, "Jane" => 22, "Bob" => 30];
asort($ages); // Sorts by values
print_r($ages); // Outputs: Array ( [Jane] => 22 [John] => 25 [Bob] => 30 )
?>
c. Using ksort()
php
Copy code
<?php
$ages = ["John" => 25, "Jane" => 22, "Bob" => 30];
ksort($ages); // Sorts by keys
print_r($ages); // Outputs: Array ( [Bob] => 30 [Jane] => 22 [John] => 25 )
?>
6. Merging Arrays
You can merge multiple arrays into one using the array_merge() function.
Example:
php
Copy code
<?php
$array1 = ["a" => "red", "b" => "green"];
$array2 = ["c" => "blue", "d" => "yellow"];
$merged = array_merge($array1, $array2);
print_r($merged); // Outputs: Array ( [a] => red [b] => green [c] => blue [d] => yellow )
?>
Page 66
PHP Programming
7. Filtering Arrays
Example:
php
Copy code
<?php
$numbers = [1, 2, 3, 4, 5];
$evens = array_filter($numbers, function($num) {
return $num % 2 == 0; // Keeps even numbers
});
print_r($evens); // Outputs: Array ( [1] => 2 [3] => 4 )
?>
8. Reducing an Array
Example:
php
Copy code
<?php
$numbers = [1, 2, 3, 4];
$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0); // 0 is the initial value
echo "Sum: $sum"; // Outputs: Sum: 10
?>
9. Searching Arrays
You can search for values in an array using functions like in_array() and array_search().
a. Using in_array()
php
Copy code
<?php
$fruits = ["Apple", "Banana", "Cherry"];
if (in_array("Banana", $fruits)) {
echo "Banana is in the array."; // Outputs: Banana is in the array.
}
?>
b. Using array_search()
Page 67
PHP Programming
php
Copy code
<?php
$fruits = ["Apple", "Banana", "Cherry"];
$key = array_search("Cherry", $fruits);
echo "Cherry is found at index: $key"; // Outputs: Cherry is found at index: 2
?>
10. Iterating Over an Array
a. Using foreach
php
Copy code
<?php
$fruits = ["Apple", "Banana", "Cherry"];
Manipulating arrays in PHP is a fundamental skill that allows you to manage collections of
data effectively. PHP provides a rich set of built-in functions and control structures to create,
modify, sort, filter, merge, and search arrays. Understanding these operations will enable you
to work efficiently with data in your PHP applications.
In PHP, you often need to work with multiple arrays simultaneously, especially when dealing
with related datasets. This chapter will cover various techniques for processing multiple
arrays together, including merging, iterating, filtering, and combining data from multiple
sources.
Page 68
PHP Programming
1. Merging Arrays
Merging arrays is useful when you want to combine data from different sources into a single
array. You can use the array_merge() function to combine indexed or associative arrays.
Example:
php
Copy code
<?php
$array1 = ["Apple", "Banana"];
$array2 = ["Cherry", "Date"];
For associative arrays, if there are duplicate keys, the values from the second array will
overwrite those from the first.
Example:
php
Copy code
<?php
$array1 = ["a" => "red", "b" => "green"];
$array2 = ["b" => "blue", "c" => "yellow"];
You can combine arrays into a new associative array where one array provides the keys and
the other provides the values using array_combine().
Example:
php
Copy code
<?php
$keys = ["name", "age", "city"];
$values = ["Alice", 30, "New York"];
Page 69
PHP Programming
When processing multiple arrays simultaneously, you can use a loop that runs through the
arrays in parallel. The for loop is often the best choice when working with indexed arrays.
Example:
php
Copy code
<?php
$names = ["Alice", "Bob", "Charlie"];
$ages = [25, 30, 35];
When dealing with associative arrays, foreach loops can be nested to handle related data.
Example:
php
Copy code
<?php
$people = [
["name" => "Alice", "age" => 25],
["name" => "Bob", "age" => 30],
["name" => "Charlie", "age" => 35],
];
You can filter data based on conditions applied across multiple arrays. For example, if you
have two arrays and want to filter based on a condition from both arrays, you can use
array_filter() with a callback function.
Page 70
PHP Programming
Example:
php
Copy code
<?php
$names = ["Alice", "Bob", "Charlie"];
$ages = [25, 30, 35];
You can join multiple arrays into a single string using implode(). This is useful for displaying
or exporting data.
Example:
php
Copy code
<?php
$array1 = ["Apple", "Banana"];
$array2 = ["Cherry", "Date"];
When working with associative arrays, it’s common to relate keys from one array to values in
another.
Example:
php
Copy code
<?php
$names = ["Alice" => 25, "Bob" => 30, "Charlie" => 35];
$salaries = ["Alice" => 50000, "Bob" => 60000, "Charlie" => 70000];
Page 71
PHP Programming
}
// Outputs:
// Alice is 25 years old and earns $50000.
// Bob is 30 years old and earns $60000.
// Charlie is 35 years old and earns $70000.
?>
7. Transposing Arrays
You might need to convert rows into columns (or vice versa) by transposing a two-
dimensional array.
Example:
php
Copy code
<?php
$data = [
["name" => "Alice", "age" => 25],
["name" => "Bob", "age" => 30],
];
$transposed = [];
foreach ($data as $row) {
foreach ($row as $key => $value) {
$transposed[$key][] = $value;
}
}
print_r($transposed);
// Outputs: Array ( [name] => Array ( [0] => Alice [1] => Bob ) [age] => Array ( [0] => 25
[1] => 30 ) )
?>
Summary
Processing multiple arrays together in PHP is an essential skill that allows for the efficient
handling of related data sets. Techniques like merging, combining, iterating, filtering, and
transposing arrays provide powerful tools for managing complex data structures.
Understanding these techniques enables you to build more dynamic and responsive
applications that can handle various data types and relationships effectively.
The DateTime class in PHP provides a flexible and robust way to work with date and time. It
simplifies the process of date manipulation, making it easier to perform operations like
formatting, comparing, and calculating differences between dates. This chapter covers the
core functionalities of the DateTime class and demonstrates how to use it effectively in your
PHP applications.
Page 72
PHP Programming
To create a new DateTime object, you can simply instantiate the class. By default, it will use
the current date and time, but you can also specify a date string.
Example:
php
Copy code
<?php
// Current date and time
$dateTimeNow = new DateTime();
echo $dateTimeNow->format('Y-m-d H:i:s') . "\n"; // Outputs current date and time
// Specifying a date
$dateTimeSpecified = new DateTime('2024-10-25 15:30:00');
echo $dateTimeSpecified->format('Y-m-d H:i:s') . "\n"; // Outputs: 2024-10-25 15:30:00
?>
2. Setting Time Zones
The DateTime class allows you to set the time zone using the DateTimeZone class. This is
crucial for applications that need to handle time in different regions.
Example:
php
Copy code
<?php
$timezone = new DateTimeZone('America/New_York');
$dateTime = new DateTime('now', $timezone);
echo $dateTime->format('Y-m-d H:i:s T') . "\n"; // Outputs the current date and time in New
York
?>
3. Formatting Dates
You can format dates using the format() method, which allows you to specify the desired
format using predefined characters.
Y - Four-digit year
m - Two-digit month
d - Two-digit day
H - Two-digit hour (24-hour format)
i - Two-digit minutes
s - Two-digit seconds
T - Timezone abbreviation
Page 73
PHP Programming
Example:
php
Copy code
<?php
$dateTime = new DateTime('2024-10-25 15:30:00');
echo $dateTime->format('d-m-Y H:i:s') . "\n"; // Outputs: 25-10-2024 15:30:00
?>
4. Modifying Dates
You can modify dates easily using the modify() method, which allows you to add or subtract
time from a DateTime object.
Example:
php
Copy code
<?php
$dateTime = new DateTime('2024-10-25');
$dateTime->modify('+1 week');
echo $dateTime->format('Y-m-d') . "\n"; // Outputs: 2024-11-01
$dateTime->modify('-2 days');
echo $dateTime->format('Y-m-d') . "\n"; // Outputs: 2024-10-30
?>
You can also use the add() and sub() methods for more clarity.
Example:
php
Copy code
<?php
$dateTime = new DateTime('2024-10-25');
$dateInterval = new DateInterval('P1D'); // 1 day interval
$dateTime->add($dateInterval);
echo $dateTime->format('Y-m-d') . "\n"; // Outputs: 2024-10-26
$dateTime->sub($dateInterval);
echo $dateTime->format('Y-m-d') . "\n"; // Outputs: 2024-10-25
?>
5. Comparing Dates
The DateTime class allows for easy date comparison using comparison operators or methods.
Example:
Page 74
PHP Programming
php
Copy code
<?php
$date1 = new DateTime('2024-10-25');
$date2 = new DateTime('2024-11-01');
You can also use the diff() method to get the difference between two dates.
Example:
php
Copy code
<?php
$date1 = new DateTime('2024-10-25');
$date2 = new DateTime('2024-11-01');
$diff = $date1->diff($date2);
echo $diff->format('%R%a days') . "\n"; // Outputs: +7 days
?>
6. Getting the Current Time
You can easily get the current date and time by creating a DateTime object without any
parameters or by using the now keyword.
Example:
php
Copy code
<?php
$currentDateTime = new DateTime();
echo $currentDateTime->format('Y-m-d H:i:s') . "\n"; // Outputs current date and time
?>
7. Working with Date Intervals
The DateInterval class represents a period of time and can be used to specify intervals for
adding or subtracting from a date.
Example:
php
Copy code
Page 75
PHP Programming
<?php
$startDate = new DateTime('2024-10-25');
$interval = new DateInterval('P1M'); // 1 month
$startDate->add($interval);
echo $startDate->format('Y-m-d') . "\n"; // Outputs: 2024-11-25
?>
8. Parsing Dates from Strings
You can create a DateTime object from a string representation of a date using the
createFromFormat() method.
Example:
php
Copy code
<?php
$dateString = '25-10-2024';
$dateTime = DateTime::createFromFormat('d-m-Y', $dateString);
echo $dateTime->format('Y-m-d') . "\n"; // Outputs: 2024-10-25
?>
9. Handling Time Zones
To work with time zones effectively, you can use the DateTimeZone class along with
DateTime.
Example:
php
Copy code
<?php
$dateTime = new DateTime('now', new DateTimeZone('Europe/London'));
echo $dateTime->format('Y-m-d H:i:s T') . "\n"; // Outputs the current date and time in
London
?>
You can also change the time zone of an existing DateTime object using the setTimezone()
method.
Example:
php
Copy code
<?php
$dateTime = new DateTime('now', new DateTimeZone('America/New_York'));
$dateTime->setTimezone(new DateTimeZone('Europe/London'));
echo $dateTime->format('Y-m-d H:i:s T') . "\n"; // Outputs current date and time in London
?>
Page 76
PHP Programming
You can easily format a DateTime object to the ISO 8601 format using the format() method.
Example:
php
Copy code
<?php
$dateTime = new DateTime('2024-10-25 15:30:00');
echo $dateTime->format(DateTime::ISO8601) . "\n"; // Outputs: 2024-10-25T15:30:00+0000
?>
Summary
The DateTime class in PHP is a powerful and versatile tool for handling date and time
manipulation. With its extensive set of methods, you can easily create, format, modify, and
compare dates, making it an essential component for any application that requires date and
time management. Understanding how to use the DateTime class will enable you to build
more sophisticated and user-friendly applications that effectively manage temporal data.
PHP provides powerful tools for handling dates and times, primarily through the DateTime
class and various related functions. This guide will cover the essential aspects of working
with dates and times in PHP, including creation, formatting, manipulation, and time zone
management.
You can create DateTime objects using the default current date and time or by specifying a
particular date string.
Example:
php
Copy code
<?php
// Current date and time
$currentDateTime = new DateTime();
echo $currentDateTime->format('Y-m-d H:i:s') . "\n"; // Outputs the current date and time
Page 77
PHP Programming
You can set time zones using the DateTimeZone class. This is important for applications that
need to handle different regional times.
Example:
php
Copy code
<?php
// Create a DateTime object with a specific time zone
$timezone = new DateTimeZone('America/New_York');
$dateTime = new DateTime('now', $timezone);
echo $dateTime->format('Y-m-d H:i:s T') . "\n"; // Outputs current date and time in New
York
?>
3. Formatting Dates
The format() method allows you to present dates and times in a specific format using
predefined characters.
Y: Four-digit year
m: Two-digit month (01-12)
d: Two-digit day of the month (01-31)
H: Hour in 24-hour format (00-23)
i: Minutes (00-59)
s: Seconds (00-59)
Example:
php
Copy code
<?php
$dateTime = new DateTime('2024-10-25 15:30:00');
echo $dateTime->format('d-m-Y H:i:s') . "\n"; // Outputs: 25-10-2024 15:30:00
?>
4. Modifying Dates and Times
You can easily modify DateTime objects using the modify() method, or by using add() and
sub() methods for better clarity.
Example:
php
Copy code
<?php
Page 78
PHP Programming
$dateTime->modify('-2 days');
echo $dateTime->format('Y-m-d') . "\n"; // Outputs: 2024-10-30
$dateTime->sub($dateInterval);
echo $dateTime->format('Y-m-d') . "\n"; // Outputs: 2024-10-30
?>
5. Comparing Dates
You can compare DateTime objects using comparison operators or the diff() method.
Example:
php
Copy code
<?php
$date1 = new DateTime('2024-10-25');
$date2 = new DateTime('2024-11-01');
You can easily retrieve the current date and time by creating a DateTime object without any
parameters or by using the now keyword.
Example:
php
Copy code
<?php
$currentDateTime = new DateTime();
Page 79
PHP Programming
DateInterval represents a period of time and can be used for adding or subtracting time from a
DateTime object.
Example:
php
Copy code
<?php
$startDate = new DateTime('2024-10-25');
$interval = new DateInterval('P1M'); // 1 month
$startDate->add($interval);
echo $startDate->format('Y-m-d') . "\n"; // Outputs: 2024-11-25
?>
8. Parsing Dates from Strings
You can create a DateTime object from a string using createFromFormat() for more complex
formats.
Example:
php
Copy code
<?php
$dateString = '25-10-2024';
$dateTime = DateTime::createFromFormat('d-m-Y', $dateString);
echo $dateTime->format('Y-m-d') . "\n"; // Outputs: 2024-10-25
?>
9. Formatting DateTime Objects to ISO 8601
You can format a DateTime object to the ISO 8601 format easily.
Example:
php
Copy code
<?php
$dateTime = new DateTime('2024-10-25 15:30:00');
echo $dateTime->format(DateTime::ISO8601) . "\n"; // Outputs: 2024-10-25T15:30:00+0000
?>
Page 80
PHP Programming
You can easily change the time zone of an existing DateTime object using the setTimezone()
method.
Example:
php
Copy code
<?php
$dateTime = new DateTime('now', new DateTimeZone('America/New_York'));
$dateTime->setTimezone(new DateTimeZone('Europe/London'));
echo $dateTime->format('Y-m-d H:i:s T') . "\n"; // Outputs current date and time in London
?>
Summary
Working with dates and times in PHP is straightforward thanks to the DateTime class and
related functions. You can create and manipulate dates, handle time zones, and format output
easily. This flexibility makes it a crucial aspect of developing robust applications that require
date and time management. Understanding these concepts will empower you to build
applications that efficiently handle various date and time-related tasks.
Control structures in PHP are essential for controlling the flow of the program. They allow
you to execute different code blocks based on conditions or repeat blocks of code. This
chapter covers the main types of control structures in PHP, including conditional statements,
loops, and switch statements.
1. Conditional Statements
1.1 If Statement
Example:
php
Copy code
<?php
$age = 20;
Page 81
PHP Programming
?>
1.2 If-Else Statement
The if-else statement allows you to execute one block of code if the condition is true and
another block if it is false.
Example:
php
Copy code
<?php
$age = 16;
Example:
php
Copy code
<?php
$grade = 85;
The switch statement is used to execute one block of code among many based on the value of
a variable.
Example:
php
Page 82
PHP Programming
Copy code
<?php
$day = 3;
switch ($day) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
default:
echo "Invalid day";
}
?>
2. Looping Structures
Example:
php
Copy code
<?php
for ($i = 0; $i < 5; $i++) {
echo "The number is: $i\n";
}
?>
2.2 While Loop
The while loop executes a block of code as long as the specified condition is true.
Example:
php
Copy code
<?php
$i = 0;
while ($i < 5) {
echo "The number is: $i\n";
$i++;
Page 83
PHP Programming
}
?>
2.3 Do-While Loop
The do-while loop executes a block of code once before checking the condition. It will
continue to execute as long as the condition is true.
Example:
php
Copy code
<?php
$i = 0;
do {
echo "The number is: $i\n";
$i++;
} while ($i < 5);
?>
2.4 Foreach Loop
Example:
php
Copy code
<?php
$colors = ["red", "green", "blue"];
Example:
php
Copy code
<?php
for ($i = 0; $i < 10; $i++) {
if ($i == 5) {
break; // Exit the loop when $i is 5
}
Page 84
PHP Programming
The continue statement skips the current iteration of a loop and moves to the next iteration.
Example:
php
Copy code
<?php
for ($i = 0; $i < 10; $i++) {
if ($i % 2 == 0) {
continue; // Skip even numbers
}
echo "Odd number: $i\n";
}
?>
Summary
Control structures in PHP allow for flexible and dynamic programming by enabling
conditional execution and repetitive tasks. Understanding how to use if, else, switch, and
various looping structures such as for, while, and foreach is essential for developing robust
applications. The ability to control the flow of your program is a fundamental concept in
programming that empowers you to create complex and interactive applications.
Loops in PHP
Loops in PHP are control structures that allow you to execute a block of code multiple times
based on certain conditions. They are essential for repetitive tasks, such as processing items
in an array, executing a block of code a specific number of times, or iterating through
collections of data. This chapter covers the different types of loops available in PHP.
1. For Loop
The for loop is used when you know in advance how many times you want to execute a
statement or a block of statements. It consists of three parts: initialization, condition, and
increment/decrement.
Page 85
PHP Programming
Syntax:
php
Copy code
for (initialization; condition; increment/decrement) {
// Code to be executed
}
Example:
php
Copy code
<?php
for ($i = 0; $i < 5; $i++) {
echo "The number is: $i\n"; // Outputs numbers from 0 to 4
}
?>
2. While Loop
The while loop repeatedly executes a block of code as long as the specified condition is true.
It checks the condition before each iteration.
Syntax:
php
Copy code
while (condition) {
// Code to be executed
}
Example:
php
Copy code
<?php
$i = 0;
while ($i < 5) {
echo "The number is: $i\n"; // Outputs numbers from 0 to 4
$i++;
}
?>
3. Do-While Loop
The do-while loop is similar to the while loop, but it guarantees that the block of code will be
executed at least once before checking the condition. The condition is evaluated after the
code block is executed.
Syntax:
Page 86
PHP Programming
php
Copy code
do {
// Code to be executed
} while (condition);
Example:
php
Copy code
<?php
$i = 0;
do {
echo "The number is: $i\n"; // Outputs numbers from 0 to 4
$i++;
} while ($i < 5);
?>
4. Foreach Loop
The foreach loop is specifically designed for iterating over arrays. It simplifies the syntax
needed to loop through each element in an array.
Syntax:
php
Copy code
foreach ($array as $value) {
// Code to be executed
}
Example:
php
Copy code
<?php
$colors = ["red", "green", "blue"];
You can also access both the key and the value in an associative array.
Example:
php
Copy code
<?php
Page 87
PHP Programming
$fruits = ["apple" => "red", "banana" => "yellow", "grape" => "purple"];
The break statement is used to exit a loop prematurely. You can also specify the number of
nested loops to exit.
Example:
php
Copy code
<?php
for ($i = 0; $i < 10; $i++) {
if ($i == 5) {
break; // Exit the loop when $i is 5
}
echo "The number is: $i\n"; // Outputs numbers from 0 to 4
}
?>
The continue statement skips the current iteration and proceeds to the next iteration of the
loop.
Example:
php
Copy code
<?php
for ($i = 0; $i < 10; $i++) {
if ($i % 2 == 0) {
continue; // Skip even numbers
}
echo "Odd number: $i\n"; // Outputs odd numbers only
}
?>
Summary
Loops are a fundamental concept in PHP that enable you to execute blocks of code repeatedly
based on specific conditions. Understanding how to use for, while, do-while, and foreach
loops will greatly enhance your ability to write efficient and effective code for various
Page 88
PHP Programming
applications. By mastering loops, you can simplify complex tasks and handle repetitive
operations with ease.
Functions in PHP are reusable blocks of code that perform a specific task. They help organize
code, improve readability, and reduce redundancy by allowing you to call the same code
multiple times with different inputs. This chapter covers the various aspects of functions in
PHP, including defining, calling, and using functions effectively.
1. Defining a Function
You define a function using the function keyword, followed by the function name,
parentheses for parameters, and a block of code enclosed in braces.
Syntax:
php
Copy code
function functionName($parameter1, $parameter2) {
// Code to be executed
}
Example:
php
Copy code
<?php
function greet($name) {
echo "Hello, $name!\n";
}
?>
2. Calling a Function
To execute the code in a function, you call it by its name followed by parentheses, including
any required arguments.
Example:
php
Copy code
<?php
greet("Alice"); // Outputs: Hello, Alice!
greet("Bob"); // Outputs: Hello, Bob!
?>
Page 89
PHP Programming
Functions can accept parameters and return values. Parameters allow you to pass data into the
function, and the return value lets the function output a result.
php
Copy code
<?php
function add($a, $b) {
return $a + $b;
}
You can set default values for function parameters. If no argument is passed for that
parameter, the default value is used.
Example:
php
Copy code
<?php
function greet($name = "Guest") {
echo "Hello, $name!\n";
}
Variables defined outside of a function have a different scope than those defined inside.
Variables inside a function are local to that function.
Example:
php
Copy code
<?php
$globalVar = "I am a global variable.";
function testScope() {
$localVar = "I am a local variable.";
Page 90
PHP Programming
testScope();
echo $globalVar . "\n"; // Outputs: I am a global variable.
// echo $localVar; // This will cause an error because $localVar is not accessible here.
?>
6. Global Keyword
To access a global variable inside a function, you can use the global keyword.
Example:
php
Copy code
<?php
$globalVar = "I am a global variable.";
function testGlobal() {
global $globalVar;
echo $globalVar . "\n"; // Outputs: I am a global variable.
}
testGlobal();
?>
7. Returning Values
A function can return a value using the return statement. Once a return statement is executed,
the function terminates.
Example:
php
Copy code
<?php
function multiply($a, $b) {
return $a * $b;
}
PHP supports anonymous functions, also known as lambda functions. These functions do not
have a name and can be assigned to variables or passed as arguments.
Example:
Page 91
PHP Programming
php
Copy code
<?php
$square = function($n) {
return $n * $n;
};
echo "The square of 4 is: " . $square(4) . "\n"; // Outputs: The square of 4 is: 16
?>
9. Function Types and Type Hinting
PHP allows you to specify the type of arguments a function accepts and the type it returns.
This feature helps enforce correct data types.
Example:
php
Copy code
<?php
function divide(float $a, float $b): float {
return $a / $b;
}
A function can call itself, which is known as recursion. This technique is useful for solving
problems that can be broken down into smaller subproblems.
Example:
php
Copy code
<?php
function factorial($n) {
if ($n <= 1) {
return 1; // Base case
}
return $n * factorial($n - 1); // Recursive case
}
Page 92
PHP Programming
Summary
Functions are a fundamental aspect of programming in PHP that promote code reusability,
modularity, and readability. By understanding how to define, call, and manipulate functions,
as well as leveraging parameters, return values, and recursion, you can create efficient and
maintainable code for your applications. Functions help in organizing code into logical
segments, making it easier to debug and enhance over time.
In functional programming, functions are treated as first-class citizens. This means that
functions can be:
Assigned to variables
Passed as arguments to other functions
Returned from other functions
Example:
php
Copy code
<?php
function greet($name) {
return "Hello, $name!";
}
Higher-order functions are functions that take other functions as arguments or return them as
results. This is a core concept in functional programming.
Example:
php
Copy code
Page 93
PHP Programming
<?php
function applyFunction($callback, $value) {
return $callback($value);
}
Anonymous functions, also known as closures, are functions that do not have a name and can
be used as values. They are often used in higher-order functions.
Example:
php
Copy code
<?php
$square = function($n) {
return $n * $n;
};
You can also use closures in conjunction with array functions like array_map and array_filter.
Example:
php
Copy code
<?php
$numbers = [1, 2, 3, 4, 5];
print_r($squared); // Outputs: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )
?>
4. Immutability
In functional programming, data is immutable, meaning it cannot be changed after it has been
created. Instead of modifying existing data, new data structures are created.
Example:
php
Page 94
PHP Programming
Copy code
<?php
function addElement($array, $element) {
// Return a new array with the element added
return array_merge($array, [$element]);
}
It always produces the same output for the same input (deterministic).
It does not have side effects (it does not modify external state or variables).
Example:
php
Copy code
<?php
function multiply($a, $b) {
return $a * $b; // Pure function
}
Functional composition is the process of combining two or more functions to produce a new
function. This allows for more modular and reusable code.
Example:
php
Copy code
<?php
function add($x) {
return function($y) use ($x) {
return $x + $y;
};
}
$add5 = add(5);
Page 95
PHP Programming
PHP provides several built-in functions that embrace functional programming concepts,
particularly for working with arrays. Common functions include:
Example of array_filter():
php
Copy code
<?php
$numbers = [1, 2, 3, 4, 5, 6];
The array_reduce() function can be used to accumulate values into a single result.
Example:
php
Copy code
<?php
$numbers = [1, 2, 3, 4];
code. Although PHP is primarily an object-oriented and procedural language, its support for
functional programming concepts provides developers with a powerful toolkit for building
efficient applications.
PHP provides an alternative syntax for control structures, which is particularly useful in
templating scenarios (like when mixing HTML and PHP). This alternative syntax uses colons
(:) instead of braces ({}) and includes an endif;, endwhile;, endforeach;, endswitch;, etc., to
mark the end of the control structure.
Here’s how you can use the alternative syntax for various control structures in PHP.
Standard Syntax:
php
Copy code
<?php
if ($condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
?>
Alternative Syntax:
php
Copy code
<?php
if ($condition):
// Code to execute if the condition is true
else:
// Code to execute if the condition is false
endif;
?>
2. Alternative Syntax for switch Statement
Standard Syntax:
php
Copy code
<?php
switch ($variable) {
case 'value1':
Page 97
PHP Programming
Alternative Syntax:
php
Copy code
<?php
switch ($variable):
case 'value1':
// Code for value1
break;
case 'value2':
// Code for value2
break;
default:
// Code for default case
endswitch;
?>
3. Alternative Syntax for for Loop
Standard Syntax:
php
Copy code
<?php
for ($i = 0; $i < 5; $i++) {
// Code to execute
}
?>
Alternative Syntax:
php
Copy code
<?php
for ($i = 0; $i < 5; $i++):
// Code to execute
endfor;
?>
Page 98
PHP Programming
Standard Syntax:
php
Copy code
<?php
foreach ($array as $value) {
// Code to execute
}
?>
Alternative Syntax:
php
Copy code
<?php
foreach ($array as $value):
// Code to execute
endforeach;
?>
5. Alternative Syntax for while Loop
Standard Syntax:
php
Copy code
<?php
while ($condition) {
// Code to execute
}
?>
Alternative Syntax:
php
Copy code
<?php
while ($condition):
// Code to execute
endwhile;
?>
6. Alternative Syntax for do-while Loop
Standard Syntax:
php
Copy code
Page 99
PHP Programming
<?php
do {
// Code to execute
} while ($condition);
?>
Alternative Syntax:
php
Copy code
<?php
do:
// Code to execute
while ($condition);
?>
Example Usage
Here’s a complete example using alternative syntax for an if statement and a foreach loop:
php
Copy code
<?php
$fruits = ['apple', 'banana', 'cherry'];
The alternative syntax for control structures in PHP provides a cleaner and more readable
way to write code, especially when mixing HTML and PHP. This syntax can be particularly
useful in templates, making your PHP code easier to maintain and understand. Whether you
choose the standard or alternative syntax is a matter of personal or project coding style
preference, but knowing both can enhance your versatility as a PHP developer.
PHP provides an alternative syntax for control structures, which is particularly useful in
templating scenarios (like when mixing HTML and PHP). This alternative syntax uses colons
Page 100
PHP Programming
(:) instead of braces ({}) and includes an endif;, endwhile;, endforeach;, endswitch;, etc., to
mark the end of the control structure.
Here’s how you can use the alternative syntax for various control structures in PHP.
Standard Syntax:
php
Copy code
<?php
if ($condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
?>
Alternative Syntax:
php
Copy code
<?php
if ($condition):
// Code to execute if the condition is true
else:
// Code to execute if the condition is false
endif;
?>
2. Alternative Syntax for switch Statement
Standard Syntax:
php
Copy code
<?php
switch ($variable) {
case 'value1':
// Code for value1
break;
case 'value2':
// Code for value2
break;
default:
// Code for default case
}
?>
Page 101
PHP Programming
Alternative Syntax:
php
Copy code
<?php
switch ($variable):
case 'value1':
// Code for value1
break;
case 'value2':
// Code for value2
break;
default:
// Code for default case
endswitch;
?>
3. Alternative Syntax for for Loop
Standard Syntax:
php
Copy code
<?php
for ($i = 0; $i < 5; $i++) {
// Code to execute
}
?>
Alternative Syntax:
php
Copy code
<?php
for ($i = 0; $i < 5; $i++):
// Code to execute
endfor;
?>
4. Alternative Syntax for foreach Loop
Standard Syntax:
php
Copy code
<?php
foreach ($array as $value) {
// Code to execute
}
?>
Page 102
PHP Programming
Alternative Syntax:
php
Copy code
<?php
foreach ($array as $value):
// Code to execute
endforeach;
?>
5. Alternative Syntax for while Loop
Standard Syntax:
php
Copy code
<?php
while ($condition) {
// Code to execute
}
?>
Alternative Syntax:
php
Copy code
<?php
while ($condition):
// Code to execute
endwhile;
?>
6. Alternative Syntax for do-while Loop
Standard Syntax:
php
Copy code
<?php
do {
// Code to execute
} while ($condition);
?>
Alternative Syntax:
php
Copy code
<?php
do:
Page 103
PHP Programming
// Code to execute
while ($condition);
?>
Example Usage
Here’s a complete example using alternative syntax for an if statement and a foreach loop:
php
Copy code
<?php
$fruits = ['apple', 'banana', 'cherry'];
The alternative syntax for control structures in PHP provides a cleaner and more readable
way to write code, especially when mixing HTML and PHP. This syntax can be particularly
useful in templates, making your PHP code easier to maintain and understand. Whether you
choose the standard or alternative syntax is a matter of personal or project coding style
preference, but knowing both can enhance your versatility as a PHP developer.
Page 104
PHP Programming
String formatting in PHP is essential for creating dynamic and readable output. PHP provides
several methods to format strings, including concatenation, interpolation, and using built-in
functions like sprintf(), printf(), and the NumberFormatter class. This chapter covers various
string formatting techniques in PHP.
1. String Concatenation
String concatenation is the process of joining two or more strings together using the dot (.)
operator.
Example:
php
Copy code
<?php
$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName;
echo $fullName; // Outputs: John Doe
?>
2. String Interpolation
String interpolation allows you to embed variables directly within double-quoted strings or
heredoc syntax. This makes it easy to create dynamic strings.
Example:
php
Copy code
<?php
$name = "Alice";
echo "Hello, $name!"; // Outputs: Hello, Alice!
?>
Using Curly Braces for Clarity: When you need to embed array elements or complex
expressions, using curly braces can help avoid ambiguity.
Example:
php
Copy code
<?php
$user = ['name' => 'Bob', 'age' => 25];
echo "User: {$user['name']} is {$user['age']} years old."; // Outputs: User: Bob is 25 years
old.
?>
Page 105
PHP Programming
3. Using sprintf()
The sprintf() function allows you to format strings with placeholders and specify how the
data should be formatted. It returns the formatted string without outputting it directly.
Example:
php
Copy code
<?php
$number = 10;
$formattedString = sprintf("The number is: %d", $number);
echo $formattedString; // Outputs: The number is: 10
?>
php
Copy code
<?php
$name = "Charlie";
$age = 30;
$formattedString = sprintf("%s is %d years old.", $name, $age);
echo $formattedString; // Outputs: Charlie is 30 years old.
?>
4. Using printf()
The printf() function works similarly to sprintf(), but it directly outputs the formatted string
instead of returning it.
Example:
php
Copy code
<?php
$temperature = 25.5;
printf("The temperature is %.1f degrees Celsius.", $temperature); // Outputs: The temperature
is 25.5 degrees Celsius.
?>
5. Formatting Numbers with number_format()
The number_format() function formats numbers with grouped thousands and a specified
number of decimal points.
Example:
php
Copy code
Page 106
PHP Programming
<?php
$number = 1234567.891;
$formattedNumber = number_format($number, 2, '.', ',');
echo $formattedNumber; // Outputs: 1,234,567.89
?>
6. Using the NumberFormatter Class
The NumberFormatter class, part of the intl extension, provides advanced options for number
formatting, including locale-specific formatting.
Example:
php
Copy code
<?php
$number = 1234567.891;
$formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, 2);
echo $formatter->format($number); // Outputs: 1,234,567.89
?>
7. Date and Time Formatting
To format dates and times, use the date() function, which formats a local date and time.
Example:
php
Copy code
<?php
$timestamp = time();
$formattedDate = date("Y-m-d H:i:s", $timestamp);
echo $formattedDate; // Outputs: Current date and time (e.g., 2024-10-25 12:34:56)
?>
Summary
String formatting in PHP is a powerful feature that allows you to create dynamic and well-
structured strings for output. By understanding various methods such as concatenation,
interpolation, and using formatting functions like sprintf(), printf(), and number_format(),
you can handle strings and numbers effectively in your PHP applications. Additionally, using
the NumberFormatter class and the date() function can enhance your ability to present data in
a user-friendly way. These string formatting techniques are essential for creating readable and
maintainable code.
Page 107
PHP Programming
String parsing is the process of analyzing and manipulating strings to extract useful
information or format them into a desired structure. PHP offers various functions and
methods for parsing strings, enabling developers to handle text data effectively. This chapter
covers key string parsing techniques in PHP.
PHP provides several basic functions for string manipulation, including strlen(), strpos(), and
substr().
Example:
php
Copy code
<?php
$string = "Hello, world!";
echo strlen($string); // Outputs: 13
echo strpos($string, "world"); // Outputs: 7
echo substr($string, 7, 5); // Outputs: world
?>
2. String Tokenization with explode()
The explode() function splits a string into an array based on a specified delimiter.
Example:
php
Copy code
<?php
$csv = "apple,banana,cherry";
$fruits = explode(",", $csv);
print_r($fruits); // Outputs: Array ( [0] => apple [1] => banana [2] => cherry )
?>
3. String Parsing with preg_split()
For more complex splitting based on regular expressions, you can use preg_split(). This
function allows you to define patterns for splitting strings.
Example:
php
Copy code
Page 108
PHP Programming
<?php
$text = "apple;banana, cherry orange";
$fruits = preg_split("/[;, ]/", $text);
print_r($fruits); // Outputs: Array ( [0] => apple [1] => banana [2] => cherry [3] => orange )
?>
4. String Replacement with str_replace()
The str_replace() function replaces occurrences of a substring within a string with a new
substring.
Example:
php
Copy code
<?php
$sentence = "The quick brown fox jumps over the lazy dog.";
$newSentence = str_replace("lazy", "energetic", $sentence);
echo $newSentence; // Outputs: The quick brown fox jumps over the energetic dog.
?>
5. Using preg_replace()
For more advanced replacements using regular expressions, preg_replace() allows you to
match patterns and replace them.
Example:
php
Copy code
<?php
$text = "2024-10-25";
$formatted = preg_replace("/(\d{4})-(\d{2})-(\d{2})/", "$3/$2/$1", $text);
echo $formatted; // Outputs: 25/10/2024
?>
6. String Searching with strpos() and strrpos()
The strpos() function finds the first occurrence of a substring, while strrpos() finds the last
occurrence.
Example:
php
Copy code
<?php
$haystack = "The quick brown fox jumps over the lazy dog.";
echo strpos($haystack, "fox"); // Outputs: 16
echo strrpos($haystack, "o"); // Outputs: 43
?>
Page 109
PHP Programming
The trim() function removes whitespace (or other specified characters) from the beginning
and end of a string.
Example:
php
Copy code
<?php
$string = " Hello, world! ";
echo trim($string); // Outputs: Hello, world!
?>
8. Changing Case
PHP provides functions to change the case of strings, including strtoupper(), strtolower(), and
ucwords().
Example:
php
Copy code
<?php
$input = "hello world";
echo strtoupper($input); // Outputs: HELLO WORLD
echo strtolower($input); // Outputs: hello world
echo ucwords($input); // Outputs: Hello World
?>
9. Parsing URL Strings with parse_url()
The parse_url() function is useful for breaking down URL strings into their components.
Example:
php
Copy code
<?php
$url = "https://www.example.com/path?arg=value#fragment";
$parsedUrl = parse_url($url);
print_r($parsedUrl);
// Outputs: Array ( [scheme] => https [host] => www.example.com [path] => /path [query]
=> arg=value [fragment] => fragment )
?>
10. JSON Parsing
When dealing with JSON data, PHP provides functions like json_encode() and json_decode()
for encoding and decoding JSON strings.
Page 110
PHP Programming
Example:
php
Copy code
<?php
$json = '{"name": "Alice", "age": 25}';
$data = json_decode($json, true); // Decodes to an associative array
echo $data['name']; // Outputs: Alice
?>
Summary
String parsing in PHP is a powerful set of techniques that allow you to manipulate and
analyze text data effectively. By leveraging functions like explode(), str_replace(),
preg_replace(), and parse_url(), you can extract, modify, and structure string data as needed.
Understanding these string parsing methods is crucial for effective PHP programming,
especially when working with user input, APIs, or database queries.
Page 111