0% found this document useful (0 votes)
7 views111 pages

PHP Programming Book Chapter

Uploaded by

Vikas Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
7 views111 pages

PHP Programming Book Chapter

Uploaded by

Vikas Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 111

PHP Programming

Bharatkumar Chhaganbhai Kanojiya


Swarrnim School of Computing & IT
PHP Programming

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.

Chapter 1: Getting started with PHP

HTML output from web server


PHP can be used to add content to HTML files. While HTML is processed directly by a web browser,
PHP scripts are executed by a web server and the resulting HTML is sent to the browser.

The following HTML markup contains a PHP statement that will add Hello World! to the output:

<! DOCTYPE html>


<html>
<head>
<title>PHP!</title>
</head>
<body>
<p><?php echo "Hello world!"; ?></p>
</body>
</html>
When this is saved as a PHP script and executed by a web server, the
following HTML will be sent to the user's browser:

<!DOCTYPE html>
<html>
<head>

<title>PHP!</title>

Page 1
PHP Programming

</head>
<body>
<p>Hello world!</p>
</body>
</html>

Section 1.2: Hello, World!


The most widely used language construct to print output in PHP is echo:

echo "Hello, World!\n";

Alternatively, you can also use print:

print "Hello, World!\n";

Both statements perform the same function, with minor differences:

echo has a void return, whereas print returns an int with a value of 1

echo can take multiple arguments (without parentheses only), whereas


print only takes one argument
echo is slightly faster than print

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:

printf("%s\n", "Hello, World!");

See Outputting the value of a variable for a comprehensive introduction of


outputting variables in PHP.

Section 1.3: Non-HTML output from web server


In some cases, when working with a web server, overriding the web
server's default content type may be required. There may be cases where
you need to send data as plain text, JSON, or XML, for 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.

Consider the following code, where we set Content-Type as text/plain:

header("Content-Type: text/plain"); echo "Hello World";

Page 2
PHP Programming

This will produce a plain text document with the following content:

Hello World

To produce JSON content, use the application/json content type instead:


header("Content-Type: application/json");

// Create a PHP data array.

$data = ["response" => "Hello World"];

// json_encode will convert it to a valid JSON string.

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";

// All headers must be sent before ANY PHP output

header("Content-Type: text/plain"); echo "


"World";

This will produce a warning:

Warning: Cannot modify header information - headers already sent by


(output started at
/dir/example.php:2) in /dir/example.php on line 3

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

Section 1.4: PHP built-in server


PHP 5.4+ comes with a built-in development server. It can be used to run
applications without having to install a production HTTP server such as
nginx or Apache. The built-in server is only designed to be used for
development and testing purposes.

It can be started by using the -S flag:

php -S <host/ip>:<port>

Example usage

1. Create an index.php file containing:

<?php

echo "Hello World from built-in PHP server";

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

[Mon Aug 15 18:20:19 2016] ::1:52455 [200]: /

Section 1.5: PHP CLI


PHP can also be run from command line directly using the CLI (Command Line
Interface).

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

The PHP CLI allows four ways to run PHP code:

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");

throw new RuntimeException("Stderr 5\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

Shell command line


$ php Example.php 2>stderr.log >stdout.log;\
echo STDOUT; cat stdout.log; echo;\
echo STDERR; cat stderr.log\

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

See: Command Line Interface (CLI)


Section 1.6: Instruction Separation
Just like most other C-style languages, each statement is terminated with a
semicolon. Also, a closing tag is used to terminate the last line of code of the PHP
block.

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" ?>

It is generally recommended to always use a semicolon and use a closing


tag for every PHP code block except the last PHP code block, if no more
code follows that PHP code block.

So, your code should basically look like this:


<?php

echo "Here we
use a
semicolon!";
echo "Here as
well!";

echo "Here as well!";

echo "Here we use a semicolon and a closing tag because more code
follows";

?>

<p>Some HTML code goes here</p>

<?php

echo "Here we
use a
semicolon!";
echo "Here as
well!";

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";

?>

<p>Some HTML code goes here</p>

<?php

echo "Here we
use a
semicolon!";
echo "Here as
well!";

echo "Here as well!";

echo "Here we use a semicolon but leave out the closing tag";

Page 7
PHP Programming

Section 1.7: PHP Tags


There are three kinds of tags to denote PHP blocks in a file. The PHP parser
is looking for the opening and (if present) closing tags to delimit the code to
interpret.

Standard Tags

These tags are the standard method to embed PHP code in a file.
<?php

echo "Hello World";

?>

PHP 5.x Version ≥ 5.4

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

PHP 5.x Version ≤ 5.6

ASP Tags

Page 8
PHP Programming

By enabling the asp_tags option, ASP-style tags can be used.

<%
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.

Variable variables are useful for mapping function/method calls:

function add($a, $b) { return $a + $b;


}

$funcName = 'add';

echo $funcName(1, 2); // outputs 3

This becomes particularly helpful in PHP classes:

Page 9
PHP Programming

It is possible, but not required to put $variableName between {}:


${$variableName} = $value;

The following examples are both equivalent and output "baz":


$fooBar = 'baz';

$varPrefix = 'foo';

echo $fooBar; // Outputs "baz"


echo ${$varPrefix . 'Bar'}; // Also outputs "baz"

Using {} is only mandatory when the name of the variable is itself an expression,
like this:

${$variableNamePart1 . $variableNamePart2} = $value;

It is nevertheless recommended to always use {}, because it's more readable.

While it is not recommended to do so, it is possible to chain this behavior:

$$$$$$$$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

Differences between PHP5 and PHP7

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.

In PHP7, dynamic variables, properties, and methods will now be evaluated


strictly in left-to-right order, as opposed to the mix of special cases in PHP5.
The examples below show how the order of evaluation has changed.

Page 10
PHP Programming

Case 1 : $$foo['bar']['baz']

PHP5 interpretation : ${$foo['bar']['baz']}

PHP7 interpretation : ($$foo)['bar']['baz']

Case 2 : $foo->$bar['baz']

PHP5 interpretation : $foo->{$bar['baz']}

PHP7 interpretation : ($foo->$bar)['baz']

Case 3 : $foo->$bar['baz']()

PHP5 interpretation : $foo->{$bar['baz']}()

PHP7 interpretation : ($foo->$bar)['baz']()

Case 4 : Foo::$bar['baz']()

PHP5 interpretation : Foo::{$bar['baz']}()

PHP7 interpretation : (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

Null can be assigned to any variable. It represents a variable with no value.

$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

This is the simplest type with only two possible values.

Page 11
PHP Programming

$foo = true;
$bar = false;

Booleans can be used to control the flow of code.

$foo = true;

if ($foo) {
echo "true";
} else {
echo "false";
}

Integer

An integer is a whole number positive or negative. It can be in used with


any number base. The size of an integer is platform-dependent. PHP does
not support unsigned integers.
$foo = -3; // negative

$foo = 0; // zero (can also be null or false (as boolean)

$foo = 123; // positive decimal

$bar = 0123; // octal = 83 decimal

$bar = 0xAB; // hexadecimal = 171 decimal

$bar = 0b1010; // binary = 10 decimal

var_dump(0123, 0xAB, 0b1010); // output: int(83) int(171) int(10)

Float

Floating point numbers, "doubles" or simply called "floats" are decimal numbers.
$foo = 1.23;

$foo = 10.0;

$bar = -INF;

$bar = NAN;

Array

An array is like a list of values. The simplest form of an array is indexed by


integer, and ordered by the index, with the first element lying at index 0.

Page 12
PHP Programming

$foo = array(1, 2, 3); // An array of integers

$bar = ["A", true, 123 => 5]; // Short array syntax, PHP 5.4+

echo $bar[0]; // Returns "A"


echo $bar[1]; // Returns true
echo $bar[123];// Returns 5 echo
$bar[1234]; /
/ Returns
null

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

A string is like an array of characters.

$foo = "bar";

Like an array, a string can be indexed to return its individual characters:

$foo = "bar";
echo $foo[0]; // Prints 'b', the first character of the string in $foo.

Object

An object is an instance of a class. Its variables and methods can be accessed


with the -> operator.

$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

Resource variables hold special handles to opened files, database


connections, streams, image canvas areas and the like (as it is stated in the
manual).

$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)

To get the type of a variable as a string, use the gettype() function:

echo gettype(1); // outputs "integer"


echo gettype(true); // "boolean"

Global variable best practices


We can illustrate this problem with the following pseudo-code

function foo() {
global $bob;
$bob->doSomething();
}

Your first question here is an obvious one

Where did $bob come from?

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

$dbConnector = new DBConnector(...);

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;

$bkp = $dbConnector; // Make backup


$dbConnector = Mock::create('DBConnector'); // Override

assertTrue(foo());

$dbConnector = $bkp; // Restore


}

How do we avoid Globals?

The best way to avoid globals is a philosophy called Dependency


Injection. This is where we pass the tools we need into the function or
class.
function foo(\Bar $bob) {

$bob->doSomething();

This is much easier to understand and maintain. There's no guessing


where $bob was set up because the caller is responsible for knowing that
(it's passing us what we need to know). Better still, we can use type
declarations to restrict what's being passed.

So we know that $bob is either an instance of the Bar class, or an instance of


a child of Bar, meaning we know we can use the methods of that class.
Combined with a standard autoloader (available since PHP 5.3), we can now
go track down where Bar is defined. PHP 7.0 or later includes expanded
type declarations, where you can also use scalar types (like int or string).

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.

There is no need to do global $variable; to access them within

functions/methods, classes or files. These PHP superglobal

variables are listed below:

$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION

Chapter 3: Variable Scope

Variable scope refers to the regions of code where a variable may be


accessed. This is also referred to as visibility. In PHP scope blocks are defined
by functions, classes, and a global scope available throughout an application.

Section 3.1: Superglobal variables


Superglobal variables are defined by PHP and can always be used from
anywhere without the global keyword.

<?php

function getPostValue($key, $default = NULL) {


// $_POST is a superglobal and can be used without
// having to specify 'global $_POST;'
if (isset($_POST[$key])) { return $_POST[$key];
}

return $default;
}

// retrieves $_POST['username']
echo getPostValue('username');

// retrieves $_POST['email'] and defaults to empty string


echo getPostValue('email', '');

Page 16
PHP Programming

Section 3.2: Static properties and variables


Static class properties that are defined with the public visibility are
functionally the same as global variables. They can be accessed from
anywhere the class is defined.

class SomeClass {

public static int $counter = 0;

// The static $counter variable can be read/written from anywhere

// and doesn't require an instantiation of the class

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 {

public static function getInstance() {

// Static variable $instance is not deleted when the


function ends

static $instance;

// Second call to this function will not get into the if-
statement,

// Because an instance of Singleton is now stored in the


$instance

// variable and is persisted through multiple calls

class SomeClass {
public static int $counter = 0;
}

// The static $counter variable can be read/written from anywhere


// and doesn't require an instantiation of the class
SomeClass::$counter += 1;

Page 17
PHP Programming

if (!$instance) {

// First call to this function will reach this line,

// because the $instance has only been declared, not


initialized

$instance = new Singleton();

return $instance;

$instance1 = Singleton::getInstance();

$instance2 = Singleton::getInstance();

// Comparing objects with the '===' operator checks whether they


are

// the same instance. Will print 'true', because the static


$instance

// variable in the getInstance() method is persisted through


multiple calls

var_dump($instance1 === $instance2);

Section 3.3: User-defined global variables


The scope outside of any function or class is the global scope. When a PHP
script includes another (using include or require) the scope remains the
same. If a script is included outside of any function or class, it's global
variables are included in the same global scope, but if a script is included
from within a function, the variables in the included script are in the scope
of the function.

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) {

// Accessing global variable from function scope

// requires this explicit statement

Page 18
PHP Programming

global $amount_of_log_calls;

// This change to the global variable is permanent

$amount_of_log_calls += 1;

echo $message;

// When in the global scope, regular global variables can be used

// without explicitly stating 'global $variable;'

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) {

// Accessing global variable from function scope

// requires this explicit statement

global $amount_of_log_calls;

// This change to the global variable is permanent

$amount_of_log_calls += 1;

echo $message;

Page 19
PHP Programming

// When in the global scope, regular global variables can be used

// without explicitly stating 'global $variable;'

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.

This means that the log_message() function could be rewritten as:


function log_message($message) {

// Access the global $amount_of_log_calls variable via the

// $GLOBALS array. No need for 'global $GLOBALS;', since it

// 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

Chapter 4: Super global Variables PHP

Superglobals are built-in variables that are always available in all scopes.

Several predefined variables in PHP are "superglobals", which means they


are available in all scopes throughout a script. There is no need to do
global $variable; to access them within functions or methods.

Page 20
PHP Programming

Section 4.1: Suberglobals explained

Introduction

Put simply, these are variables that are available in all scope in your scripts.

This means that there is no need to pass them as parameters in your


functions, or store them outside a block of code to have them available in
different scopes.

What's a superglobal??

If you're thinking that these are like superheroes - they're not.

As of PHP version 7.1.3 there are 9 superglobal variables. They are as follows:

$GLOBALS - References all variables available in global scope


$_SERVER - Server and execution environment information
$_GET - HTTP GET variables

$_POST - HTTP POST variables

$_FILES - HTTP File Upload variables

$_COOKIE - HTTP Cookies

$_SESSION - Session variables

$_REQUEST - HTTP Request variables

$_ENV - Environment variables

See the documentation


Tell me more, tell me more

I'm sorry for the Grease reference! Link

Time for some explanation on these superheroesglobals.


$GLOBALS

An associative array containing references to all variables which are


currently defined in the global scope of the script. The variable
names are the keys of the array.

Code
$myGlobal = "global"; // declare variable outside of scope

Page 21
PHP Programming

function test()

$myLocal = "local"; // declare variable inside of scope

// both variables are printed

var_dump($myLocal);

var_dump($GLOBALS["myGlobal"]);

test(); // run function

// only $myGlobal is printed since $myLocal is not globally scoped

var_dump($myLocal
);
var_dump($myGlob
al);

Output

string 'local' (length=5) string 'global' (length=6) null


string 'global' (length=6)

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"]);

The global keyword is a prefix on a variable that forces it to be part of the


global scope.

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").

Option two: $GLOBALS array


function test()

$GLOBALS["myLocal"] = "local";

$myLocal =
$GLOBALS["my
Local"];
var_dump($my
Local);
var_dump($GLO
BALS["myGlob
al"]);

In this example I reassigned $myLocal the value of $GLOBAL["myLocal"] since


I find it easier writing a variable name rather than the associative array.
$_SERVER

$_SERVER is an array containing information such as headers,


paths, and script locations. The entries in this array are created by
the web server. There is no guarantee that every web server will
provide any of these; servers may omit some, or provide others
not listed here. That said, a large number of these

variables are accounted for in the CGI/1.1 specification, so you should be


able to expect those.

An example output of this might be as follows (run on my Windows PC using


WAMP)
C:\wamp64\www\test.php:2:

array (size=36)

'HTTP_HOST' => string


'localhost' (length=9)
'HTTP_CONNECTION' => string
'keep-alive' (length=10)

Page 23
PHP Programming

'HTTP_CACHE_CONTROL' =>
string 'max-age=0' (length=9)
'HTTP_UPGRADE_INSECURE_REQU
ESTS' => string '1' (length=1)

'HTTP_USER_AGENT' => string 'Mozilla/5.0 (Windows NT 10.0;


WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133
Safari/537.36' (length=110)

'HTTP_ACCEPT' => string


'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*
/*;q=0.8' (length=74)

'HTTP_ACCEPT_ENCODING' => string 'gzip, deflate,


sdch, br' (length=23) 'HTTP_ACCEPT_LANGUAGE' =>
string 'en-US,en;q=0.8,en-GB;q=0.6' (length=26)
'HTTP_COOKIE' => string
'PHPSESSID=0gslnvgsci371ete9hg7k9ivc6' (length=36)

'PATH' => string 'C:\Program Files (x86)\NVIDIA Corporation\PhysX\


Common;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\
iCLS Client\;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\
WINDOWS;C:\WINDOWS\System32\Wbem

;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)

'SystemRoot' => string 'C:\WINDOWS' (length=10)

'COMSPEC' => string 'C:\WINDOWS\system32\cmd.exe' (length=27)

'PATHEXT' => string


'.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY'
(length=57)

'WINDIR' => string 'C:\WINDOWS' (length=10)

'SERVER_SIGNATURE' => string '<address>Apache/2.4.23 (Win64)


PHP/7.0.10 Server at localhost Port 80</address>' (length=80)

'SERVER_SOFTWARE' => string 'Apache/2.4.23


(Win64) PHP/7.0.10' (length=32) 'SERVER_NAME' =>
string 'localhost' (length=9)

'SERVER_ADDR' =>
string '::1'
(length=3)
'SERVER_PORT' =>
string '80' (length=2)
'REMOTE_ADDR' =>
string '::1'
(length=3)

'DOCUMENT_ROOT' => string


'C:/wamp64/www' (length=13)
'REQUEST_SCHEME' => string
'http' (length=4)
'CONTEXT_PREFIX' => string ''
(length=0)

Page 24
PHP Programming

'CONTEXT_DOCUMENT_ROOT' => string


'C:/wamp64/www' (length=13)
'SERVER_ADMIN' => string
'wampserver@wampserver.invalid'
(length=29) 'SCRIPT_FILENAME' => string
'C:/wamp64/www/test.php' (length=26)
'REMOTE_PORT' => string '5359' (length=4)

'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;)

For all explanations below, assume the URL is

http://www.example.com/index.php

HTTP_HOST - The host address.

This would return www.example.com

HTTP_USER_AGENT - Contents of the user agent. This is a string which contains


all the information about the client's browser, including operating system.
HTTP_COOKIE - All cookies in a concatenated string, with a
semi-colon delimiter. SERVER_ADDR - The IP address of the
server, of which the current script is running. This would
return 93.184.216.34
PHP_SELF - The file name of the currently executed script,

Page 25
PHP Programming

relative to document root. This would return /index.php


REQUEST_TIME_FLOAT - The timestamp of the start of the request, with
microsecond precision. Available since PHP 5.4.0.
REQUEST_TIME - The timestamp of the start of the request. Available since PHP 5.1.0.

$_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.

Using some code for those that don't like reading.


// URL =
echo $_GET["myVar"] == "myVal" ? "true" : "false"; // returns "true"

The above example makes use of the ternary operator.

This shows how you can access the value

from the URL using the $_GET superglobal.

Now another example! gasp


// URL = http://www.example.com/index.php?
myVar=myVal&myVar2=myVal2
echo $_GET["myVar"]; // returns "myVal"
echo $_GET["myVar2"]; // returns "myVal2"

It is possible to send multiple variables through the URL by


separating them with an ampersand (&) character.

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

An associative array of variables passed to the


current script via the HTTP POST method when using
application/x-www-form-urlencoded or
multipart/form-data as the HTTP Content-Type in the
request.

Very similar to $_GET in that data is sent from one place to


another.

I'll start by going straight into an example. (I have omitted the


action attribute as this will send the information to the page
that the form is in).

Security risk
Sending data via POST is also not secure. Using HTTPS will ensure
that data is kept more secure.

$_FILES

An associative array of items uploaded to the current


script via the HTTP POST method. The structure of this
array is outlined in the POST method uploads
section.

Let's start with a basic form.


<form method="POST" enctype="multipart/form-data">
<input type="file" name="myVar" />
<input type="submit" name="Submit" />
</form>
Note that I omitted the action attribute (again!). Also, I added
enctype="multipart/form-data", this is important to any form that
will be dealing with file uploads.

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.

setcookie("name", "new_value", time() + 7200, "/");

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.

setcookie("name", "", time() - 3600, "/");

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.

Use Cases for Cookies

 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
?>

2. Storing Data in a Session

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
?>

3. Accessing Session Data

You can retrieve session data on any page after calling session_start().

<?php
session_start();
echo "Username: " . $_SESSION["username"];
echo "Email: " . $_SESSION["email"];
?>

4. Modifying Session Data

To update a session variable, simply assign a new value to it in $_SESSION.

<?php
session_start();
$_SESSION["username"] = "JaneDoe"; // Update session variable
?>

Page 30
PHP Programming

5. Unsetting or Deleting a Session Variable

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
?>

Important Session Management Tips

 session_start() Required on Each Page: Call session_start() at the beginning


of each page where session data is needed.
 Session Lifetime: Sessions remain active until the browser is closed or the session
times out (configured in PHP php.ini).
 Storing Sensitive Data: Sessions are stored server-side, making them more secure
than cookies, but avoid storing excessive or highly sensitive information without
implementing security best practices.
 Regenerate Session ID: Use session_regenerate_id(true) periodically,
especially after logging in, to prevent session fixation attacks.

Example Usage: Login System

Here’s a simple example of how sessions can be used for user login.

login.php

<?php
session_start();

Page 31
PHP Programming

if ($_POST["username"] == "JohnDoe" && $_POST["password"] ==


"password123") {
$_SESSION["loggedin"] = true;
$_SESSION["username"] = "JohnDoe";
header("Location: dashboard.php");
exit;
} else {
echo "Invalid login!";
}
?>
<?php
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
header("Location: login.php");
exit;
}
echo "Welcome, " . $_SESSION["username"];
?>

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.

Chapter 5 Outputting the Value of a Variable in php

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

echo is the simplest and most common way to output a variable.

<?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)

$names = array("Alice", "Bob");

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
?>

Choosing the Right Method

 echo / print: For simple variable output.


 print_r: For arrays or objects when debugging.
 var_dump: For detailed information, especially useful for debugging.
 printf / sprintf: For formatted output.

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

Unlike variables, constants do not use a $ symbol when accessed.

<?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).

define("GREETING", "Hello, World!", true);


echo GREETING; // Outputs: Hello, World!
echo greeting; // Outputs: Hello, World! (in case-insensitive mode only)

Page 35
PHP Programming

Using const to Define Constants

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
?>

Constant Arrays (PHP 5.6+)

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.

 __LINE__: The current line number of the file.


 __FILE__: The full path and filename of the file.
 __DIR__: The directory of the file.
 __FUNCTION__: The name of the function.
 __CLASS__: The name of the class.
 __TRAIT__: The name of the trait.
 __METHOD__: The class method name.
 __NAMESPACE__: The name of the current namespace.

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

 Constants are defined using define() or const.


 They are globally accessible and immutable.

Page 36
PHP Programming

 Constants are often used for fixed configuration values.


 Magic constants provide useful metadata about the code’s structure and context.

Chapter 7: Magic Constants

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.

Here’s a breakdown of commonly used magic constants in PHP:

1. __LINE__

 Returns the current line number in the file where it is used.

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__

 Returns the name of the function in which it is called.

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__

 Returns the name of the class in which it is used.


 Returns an empty string if used outside a class context.

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__

 Returns the name of the trait in which it is used.


 Useful when working with traits for code reuse in PHP.

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__

 Returns the name of the current namespace in which it is called.


 Returns an empty string if there’s no namespace defined.

php
Copy code
<?php
namespace MyNamespace;
echo "The namespace is " . __NAMESPACE__; // Outputs: The namespace is MyNamespace
?>
Summary of Magic Constants
Magic Constant Description

__LINE__ Current line number in the file.

__FILE__ Full path and filename of the file.

__DIR__ Directory of the file without the file name.

__FUNCTION__ Name of the current function.

__CLASS__ Name of the current class.

__TRAIT__ Name of the current trait.

__METHOD__ Name of the current class method.

__NAMESPACE__ Name of the current namespace.

Practical Uses of Magic Constants

 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

* @param int $a The first number


* @param int $b The second number
* @return int The sum of the two numbers
*/
function add($a, $b) {
return $a + $b;
}
Summary of Comment Types in PHP
Type Syntax Purpose

Single-Line // or # Brief comments on a single line.

Multi-Line /* ... */ Comments that span multiple lines.

PHPDoc Comments /** ... */ Structured comments for documentation.

Use Cases

 Explain Logic: Describe complex logic or calculations.


 Add Notes: Make notes on possible improvements or future changes.
 Disable Code Temporarily: Comment out lines of code for testing/debugging
without deleting them.
 Document Code: Use PHPDoc for creating clear documentation of functions, classes,
and parameters.

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

 Represents whole numbers (positive or negative).


 Examples: 42, -7
 Range depends on the platform, typically from -2^31 to 2^31-1 on 32-bit systems.

php
Copy code
<?php
$age = 25;
echo $age; // Outputs: 25

Page 41
PHP Programming

?>
b. Float (Double)

 Represents numbers with decimal points (floating-point numbers).


 Examples: 3.14, -2.5, 1.2e3 (scientific notation).

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

 Represents two possible values: true or false.

php
Copy code
<?php
$is_active = true;
$is_admin = false;
?>
2. Compound Types

These types can hold multiple values or complex structures.

a. Array

 Represents a collection of values, which can be indexed (numerically) or associative


(key-value pairs).

php
Copy code
<?php
$fruits = array("Apple", "Banana", "Orange");
$person = array("name" => "John", "age" => 30);

Page 42
PHP Programming

echo $fruits[1]; // Outputs: Banana


echo $person["name"]; // Outputs: John
?>
b. Object

 Represents an instance of a class, containing both data (properties) and functions


(methods).

php
Copy code
<?php
class Car {
public $brand;
public function drive() {
echo "Driving...";
}
}

$myCar = new Car();


$myCar->brand = "Toyota";
echo $myCar->brand; // Outputs: Toyota
$myCar->drive(); // Outputs: Driving...
?>
3. Special Types

a. NULL

 Represents a variable with no value (an empty or undefined state).

php
Copy code
<?php
$nothing = NULL;
echo $nothing; // Outputs nothing
?>
b. Resource

 Represents external resources like file handles, database connections, or streams.


 Resources are special variables that refer to external entities.

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

 Indicates that a variable can hold values of multiple types.

b. Callable

 Represents anything that can be called as a function, like functions or methods.

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.

Function with type declarations:


php
Copy code
<?php
function add(int $a, int $b): int {
return $a + $b;
}
echo add(3, 4); // Outputs: 7
?>
Summary of PHP Types
Type Description Example

Integer Whole numbers 42, -5

Float Decimal numbers 3.14, 2.5

String Sequence of characters "Hello"

Boolean true or false values true, false

Array Collection of values ["Apple", "Banana"]

Object Instance of a class $myCar

NULL Represents a variable with no value NULL

Resource External resources (files, databases, etc.) fopen()

Understanding these types and how to work with them is crucial to effective PHP
programming.

Chapter 10: Operators

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

These operators are used to perform basic mathematical operations.

Operator Name Description Example

+ Addition Adds two values $a + $b

Page 45
PHP Programming

Operator Name Description Example

- Subtraction Subtracts one value from another $a - $b

* Multiplication Multiplies two values $a * $b

/ Division Divides one value by another $a / $b

% Modulus Returns the remainder of division $a % $b

** Exponentiation Raises one value to the power of another $a ** $b

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

Assignment operators are used to assign values to variables.

Operator Name Description Example

= Assignment Assigns a value to a variable $a = $b

+= Addition Adds the right operand to the left operand $a += $b

-= Subtraction Subtracts the right operand from the left operand $a -= $b

*= Multiplication Multiplies the left operand by the right operand $a *= $b

/= Division Divides the left operand by the right operand $a /= $b

Divides the left operand by the right operand, remainder


%= Modulus $a %= $b
assigned

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

These operators are used to compare two values.

Operator Name Description Example

== Equal Returns true if both values are equal $a == $b

=== Identical Returns true if both values and types are equal $a === $b

!= Not equal Returns true if values are not 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

<=> Spaceship Returns -1, 0, or 1 based on comparison $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

These operators are used to combine conditional statements.

Operator Name Description Example

&& And Returns true if both operands are true $a && $b

` ` Or

! Not Negates the value of an expression !$a

And (low
and Same as && but with lower precedence $a and $b
precedence)

or Or (low precedence) Same as `

Returns true if one of the operands is true, but not


xor Exclusive Or $a xor $b
both

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

These operators are used to increase or decrease the value of a variable by 1.

Operator Name Description Example

++$a Pre-increment Increments $a by 1, then returns $a ++$a

$a++ Post-increment Returns $a, then increments $a by 1 $a++

--$a Pre-decrement Decrements $a by 1, then returns $a --$a

$a-- Post-decrement Returns $a, then decrements $a by 1 $a--

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

These operators are used to manipulate strings.

Operator Name Description Example

. Concatenation Concatenates two strings $a . $b

.= Concatenation assignment Appends the right operand to the left operand $a .= $b

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

These operators are used to compare arrays.

Operator Name Description Example

+ Union Union of two arrays $a + $b

== Equality Returns true if arrays have the same key-value pairs $a == $b

Returns true if arrays are identical in both key-value pairs and


=== Identity $a === $b
order

!= Inequality Returns true if arrays are not equal $a != $b

!== Non-identity Returns true if arrays are not identical $a !== $b

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

These operators are used to perform bit-level operations.

Operator Name Description Example

& And Bitwise AND $a & $b

` ` Or Bitwise OR

^ Xor Bitwise XOR $a ^ $b

~ Not Bitwise Not ~$a

<< Left shift Shift bits

Chapter 11: References

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

$b = 20; // Modifying $b also changes $a


echo $a; // Outputs: 20
?>
Key Points about References

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.

Example of Passing by Reference:


php
Copy code
<?php
function increment(&$value) {
$value++;
}

$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

$array2[0] = 10; // Modify the first element of $array2


echo $array1[0]; // Outputs: 10 (original array is modified)
?>

4. Reference Assignment: When assigning one variable to another, a reference creates


an alias instead of copying the value.

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

echo $a; // Outputs: 5 (still exists)


?>

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

 You cannot reference constants or literals.


 You cannot reference a variable that is a result of a function call.
 References are not the same as pointers in C or C++. They have a different behavior
and are managed differently in PHP.

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.

Chapter 12: Arrays

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+)

echo $fruits[0]; // Outputs: Apple


echo $colors[1]; // Outputs: Green
?>
2. Associative Arrays

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"
);

echo $person["name"]; // Outputs: John


echo $person["age"]; // Outputs: 30
?>

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)
);

echo $students[1]["name"]; // Outputs: Bob


?>
Array Functions

PHP provides a wide range of built-in functions to manipulate arrays.

a. Creating Arrays

 array(): Creates an array.


 []: Short array syntax (PHP 5.4+).

b. Adding Elements

 array_push(): Adds one or more elements to the end of an array.


 $array[] = $value;: Appends a value to the end of an array.

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

 array_pop(): Removes the last element from an array.


 array_shift(): Removes the first element from an array.
 unset(): Removes a specific element from an array.

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

 count(): Returns the number of elements in an array.

php
Copy code
<?php
$fruits = array("Apple", "Banana", "Cherry");
echo count($fruits); // Outputs: 3
?>
e. Sorting Arrays

 sort(): Sorts an indexed array in ascending order.


 asort(): Sorts an associative array in ascending order, maintaining key-value
associations.
 ksort(): Sorts an associative array by key.

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

 array_merge(): Merges one or more arrays into one.

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

 in_array(): Checks if a value exists in an array.

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

You can use various methods to loop through arrays.

a. foreach Loop

The foreach loop is specifically designed for iterating over arrays.

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.

Chapter 13: Array iteration

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");

foreach ($fruits as $fruit) {


echo $fruit . " ";
}
// Outputs: Apple Banana Cherry
?>
Iterating with Keys:

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");

foreach ($person as $key => $value) {


echo "$key: $value\n";
}
// Outputs:
// name: John

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);

for ($i = 0; $i < count($numbers); $i++) {


echo $numbers[$i] . " ";
}
// Outputs: 1 2 3 4
?>
3. while Loop

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");

reset($colors); // Reset the array pointer


while (list($key, $value) = each($colors)) {
echo "$key: $value\n";
}
// Outputs:
// 0: Red
// 1: Green

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);

print_r($squared); // Outputs: Array ( [0] => 1 [1] => 4 [2] => 9 )


?>
6. array_walk()

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");

array_walk($fruits, function($value, $key) {


echo "$key: $value\n";
});
// Outputs:
// 0: Apple
// 1: Banana
// 2: Cherry
?>
7. array_reduce()

array_reduce() iteratively reduces an array to a single value using a callback function.

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);

echo $sum; // Outputs: 10


?>
Summary

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.

Chapter 14: Executing Upon an Array

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

You can add elements to an array using various methods.

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

array_pop($fruits); // Removes Cherry


print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana )
?>
b. Using array_shift()
php
Copy code
<?php
$fruits = ["Apple", "Banana", "Cherry"];
array_shift($fruits); // Removes Apple
print_r($fruits); // Outputs: Array ( [0] => Banana [1] => Cherry )
?>
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. Iterating Over an Array

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"];

foreach ($fruits as $fruit) {


echo $fruit . " ";
}
// Outputs: Apple Banana Cherry
?>
Using array_map()
php
Copy code
<?php
$fruits = ["Apple", "Banana", "Cherry"];
$upperFruits = array_map('strtoupper', $fruits); // Converts to uppercase
print_r($upperFruits); // Outputs: Array ( [0] => APPLE [1] => BANANA [2] => CHERRY )
?>
5. Sorting an Array

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

You can merge arrays 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 )
?>
8. Filtering Arrays

You can filter arrays using array_filter() to apply a callback function.

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

You can reduce an array to a single value using array_reduce().

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.

Chapter 15: Manipulating an Array

Manipulating arrays in PHP involves performing operations such as adding, removing,


modifying, sorting, filtering, and merging elements. PHP provides a rich set of built-in
functions that make it easy to manipulate arrays. Here’s a comprehensive guide on various
array manipulation techniques in PHP, along with examples.

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

// Creating an indexed array


$fruits = array("Apple", "Banana", "Cherry");

// Creating an associative array


$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];

print_r($fruits);
print_r($person);
?>
2. Adding Elements to an Array

a. Using array_push()

Adds one or more elements to the end of an array.

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

Appends an element to the end of an array.

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()

Adds one or more elements to the beginning of an array.

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

3. Removing Elements from an Array

a. Using array_pop()

Removes the last element from an array.

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()

Removes the first element from an array.

php
Copy code
<?php
array_shift($fruits); // Removes Apple
print_r($fruits); // Outputs: Array ( [0] => Banana )
?>
c. Using unset()

Removes a specific element from an array using its index.

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()

Sorts an indexed array in ascending order.

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()

Sorts an associative array in ascending order, maintaining key-value associations.

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()

Sorts an associative array by keys.

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

You can filter arrays based on a condition using array_filter().

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

You can reduce an array to a single value using array_reduce().

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()

Checks if a value exists in an 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()

Searches for a value in an array and returns the corresponding key.

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

You can iterate over an array using various methods.

a. Using foreach
php
Copy code
<?php
$fruits = ["Apple", "Banana", "Cherry"];

foreach ($fruits as $fruit) {


echo $fruit . " ";
}
// Outputs: Apple Banana Cherry
?>
b. Using for
php
Copy code
<?php
$numbers = [1, 2, 3, 4];
for ($i = 0; $i < count($numbers); $i++) {
echo $numbers[$i] . " ";
}
// Outputs: 1 2 3 4
?>
Summary

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.

Chapter 16: Processing Multiple Arrays Together

Chapter 16: Processing Multiple Arrays Together in PHP

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"];

$merged = array_merge($array1, $array2);


print_r($merged); // Outputs: Array ( [0] => Apple [1] => Banana [2] => Cherry [3] =>
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"];

$merged = array_merge($array1, $array2);


print_r($merged); // Outputs: Array ( [a] => red [b] => blue [c] => yellow )
?>
2. Combining Arrays

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"];

$combined = array_combine($keys, $values);


print_r($combined); // Outputs: Array ( [name] => Alice [age] => 30 [city] => New York )
?>

Page 69
PHP Programming

3. Iterating Over Multiple Arrays

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];

for ($i = 0; $i < count($names); $i++) {


echo $names[$i] . " is " . $ages[$i] . " years old.\n";
}
// Outputs:
// Alice is 25 years old.
// Bob is 30 years old.
// Charlie is 35 years old.
?>

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],
];

foreach ($people as $person) {


echo $person["name"] . " is " . $person["age"] . " years old.\n";
}
// Outputs:
// Alice is 25 years old.
// Bob is 30 years old.
// Charlie is 35 years old.
?>
4. Filtering with Multiple Arrays

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];

$filtered = array_filter($ages, function($age, $index) use ($names) {


return $age > 28 && $names[$index] !== "Bob";
}, ARRAY_FILTER_USE_BOTH);

print_r($filtered); // Outputs: Array ( [2] => 35 )


?>
5. Joining Multiple Arrays

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"];

$merged = array_merge($array1, $array2);


$resultString = implode(", ", $merged);
echo $resultString; // Outputs: Apple, Banana, Cherry, Date
?>
6. Associative Array Processing

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];

foreach ($names as $name => $age) {


if (isset($salaries[$name])) {
echo "$name is $age years old and earns $" . $salaries[$name] . ".\n";
}

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.

Chapter 17: Datetime Class

Chapter 17: The DateTime Class in PHP

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

1. Creating DateTime Objects

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.

Common format 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');

if ($date1 < $date2) {


echo "Date1 is earlier than Date2.\n"; // Outputs this line
} else {
echo "Date1 is later than or the same as Date2.\n";
}
?>

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

10. Formatting DateTime Objects to ISO 8601

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.

Chapter 18: Working with Dates and Time

Working with Dates and Time in PHP

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.

1. Creating Date and Time Objects

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

// Specifying a specific date and time


$specificDateTime = new DateTime('2024-10-25 15:30:00');
echo $specificDateTime->format('Y-m-d H:i:s') . "\n"; // Outputs: 2024-10-25 15:30:00
?>

Page 77
PHP Programming

2. Working with Time Zones

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.

Common Format 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 = 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

// Using add() and sub()


$dateInterval = new DateInterval('P1D'); // 1 day interval
$dateTime->add($dateInterval);
echo $dateTime->format('Y-m-d') . "\n"; // Outputs: 2024-10-31

$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');

if ($date1 < $date2) {


echo "Date1 is earlier than Date2.\n"; // Outputs this line
} else {
echo "Date1 is later than or the same as Date2.\n";
}

// Using diff() to find the difference


$diff = $date1->diff($date2);
echo $diff->format('%R%a days') . "\n"; // Outputs: +7 days
?>
6. Getting the Current Date and Time

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

echo $currentDateTime->format('Y-m-d H:i:s') . "\n"; // Outputs current date and time


?>
7. Date Intervals

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

10. Working with Different Time Zones

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.

Chapter 19: Control Structures in php

Control Structures in PHP

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

Conditional statements let you execute code based on certain conditions.

1.1 If Statement

The if statement executes a block of code if a specified condition is true.

Example:

php
Copy code
<?php
$age = 20;

if ($age >= 18) {


echo "You are an adult.";
}

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;

if ($age >= 18) {


echo "You are an adult.";
} else {
echo "You are a minor.";
}
?>
1.3 If-Elseif-Else Statement

You can chain multiple conditions using elseif.

Example:

php
Copy code
<?php
$grade = 85;

if ($grade >= 90) {


echo "A";
} elseif ($grade >= 80) {
echo "B";
} elseif ($grade >= 70) {
echo "C";
} else {
echo "D";
}
?>
1.4 Switch Statement

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

Looping structures allow you to execute a block of code multiple times.

2.1 For Loop

The for loop executes a block of code a specific number of times.

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

The foreach loop is specifically designed for iterating over arrays.

Example:

php
Copy code
<?php
$colors = ["red", "green", "blue"];

foreach ($colors as $color) {


echo "Color: $color\n";
}
?>
3. Break and Continue Statements

3.1 Break Statement

The break statement is used to exit a loop or switch statement.

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

echo "The number is: $i\n";


}
?>

3.2 Continue Statement

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.

Chapter 20: Loops

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"];

foreach ($colors as $color) {


echo "Color: $color\n"; // Outputs each color in the array
}
?>

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"];

foreach ($fruits as $fruit => $color) {


echo "The $fruit is $color.\n"; // Outputs the fruit and its color
}
?>

5. Breaking and Continuing Loops

5.1 Break Statement

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
}
?>

5.2 Continue Statement

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.

Chapter 21: Functions


Functions in PHP

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

3. Function Parameters and Return Values

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.

Example with Parameters:

php
Copy code
<?php
function add($a, $b) {
return $a + $b;
}

$result = add(5, 10);


echo "The sum is: $result\n"; // Outputs: The sum is: 15
?>
4. Default Parameters

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";
}

greet(); // Outputs: Hello, Guest!


greet("Alice"); // Outputs: Hello, Alice!
?>
5. Variable Scope

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

echo $localVar . "\n"; // Outputs: I am a local variable.


}

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;
}

$result = multiply(4, 5);


echo "The product is: $result\n"; // Outputs: The product is: 20
?>
8. Anonymous Functions (Lambda Functions)

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;
}

echo divide(10.0, 2.0) . "\n"; // Outputs: 5


// echo divide(10, '2'); // This will cause a TypeError in strict mode.
?>
10. Recursion

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
}

echo "Factorial of 5 is: " . factorial(5) . "\n"; // Outputs: 120


?>

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.

Chapter 22: Functional Programming


Functional Programming in PHP

Functional programming (FP) is a programming paradigm that treats computation as the


evaluation of mathematical functions and avoids changing state and mutable data. In PHP,
you can adopt functional programming concepts to improve code clarity, maintainability, and
testability. This chapter explores key aspects of functional programming in PHP, including
functions as first-class citizens, higher-order functions, immutability, and more.

1. Functions as First-Class Citizens

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!";
}

// Assigning a function to a variable


$greetingFunction = 'greet';
echo $greetingFunction('Alice'); // Outputs: Hello, Alice!
?>
2. Higher-Order Functions

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);
}

echo applyFunction('strtoupper', 'hello'); // Outputs: HELLO


?>
3. Anonymous Functions (Closures)

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;
};

echo $square(4); // Outputs: 16


?>

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];

// Using array_map with an anonymous function


$squared = array_map(function($n) {
return $n * $n;
}, $numbers);

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]);
}

$originalArray = [1, 2, 3];


$newArray = addElement($originalArray, 4);

print_r($originalArray); // Outputs: Array ( [0] => 1 [1] => 2 [2] => 3 )


print_r($newArray); // Outputs: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
?>
5. Pure Functions

A pure function is a function that has the following characteristics:

 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
}

echo multiply(5, 10); // Outputs: 50


?>
6. Functional Composition

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

echo $add5(10); // Outputs: 15


?>
7. Array Functions

PHP provides several built-in functions that embrace functional programming concepts,
particularly for working with arrays. Common functions include:

 array_map(): Applies a callback to the elements of an array.


 array_filter(): Filters elements of an array using a callback.
 array_reduce(): Reduces an array to a single value using a callback.

Example of array_filter():

php
Copy code
<?php
$numbers = [1, 2, 3, 4, 5, 6];

// Filtering even numbers


$evens = array_filter($numbers, function($n) {
return $n % 2 === 0;
});

print_r($evens); // Outputs: Array ( [1] => 2 [3] => 4 [5] => 6 )


?>
8. Using array_reduce()

The array_reduce() function can be used to accumulate values into a single result.

Example:

php
Copy code
<?php
$numbers = [1, 2, 3, 4];

// Summing the numbers


$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0);

echo $sum; // Outputs: 10


?>
Summary

Functional programming in PHP encourages a programming style that is declarative and


focuses on the use of pure functions, immutability, and higher-order functions. By adopting
functional programming principles, you can write cleaner, more maintainable, and reusable
Page 96
PHP Programming

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.

Chapter 23: Alternative Syntax for Control Structures


Alternative Syntax for Control Structures in PHP

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.

1. Alternative Syntax for if Statement

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

// Code for value1


break;
case 'value2':
// Code for value2
break;
default:
// Code for default case
}
?>

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

4. Alternative Syntax for foreach Loop

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'];

if (count($fruits) > 0):


echo "List of fruits:\n";
foreach ($fruits as $fruit):
echo "- $fruit\n";
endforeach;
else:
echo "No fruits available.";
endif;
?>
Summary

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.

Chapter 24: String formatting


Alternative Syntax for Control Structures in PHP

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.

1. Alternative Syntax for if Statement

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'];

if (count($fruits) > 0):


echo "List of fruits:\n";
foreach ($fruits as $fruit):
echo "- $fruit\n";
endforeach;
else:
echo "No fruits available.";
endif;
?>
Summary

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

Chapter 25 String Formatting in PHP

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
?>

Using Multiple Placeholders:

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 = new NumberFormatter('en_US', NumberFormatter::DECIMAL);


echo $formatter->format($number); // Outputs: 1,234,567.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

25 String Parsing in PHP

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.

1. Basic String Functions

PHP provides several basic functions for string manipulation, including strlen(), strpos(), and
substr().

 strlen(): Returns the length of a string.


 strpos(): Finds the position of the first occurrence of a substring.
 substr(): Returns a portion of a string.

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

7. Trimming Strings with trim()

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

You might also like