0% found this document useful (0 votes)
10 views

PHP Tutorial_Saleh_4Q_Part (1)

PHP is a widely-used server scripting language that enables the creation of dynamic and interactive web pages. It is free, open-source, and can run on various platforms, making it a popular choice for web development. The document covers PHP syntax, variables, comments, and installation, providing examples and exercises for learning purposes.

Uploaded by

ahmeddhamed179
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

PHP Tutorial_Saleh_4Q_Part (1)

PHP is a widely-used server scripting language that enables the creation of dynamic and interactive web pages. It is free, open-source, and can run on various platforms, making it a popular choice for web development. The document covers PHP syntax, variables, comments, and installation, providing examples and exercises for learning purposes.

Uploaded by

ahmeddhamed179
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

PHP Tutorial

• PHP is a server scripting language, and a powerful tool for making dynamic and interactive
Web pages.
• PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.

Start learning PHP now »


Get your own PHP Server

Example
<!DOCTYPE html>
<html>
<body>

<?php
echo "My first PHP script!";
?>

</body>
</html>

Try it Yourself »

Exercise?
What does PHP stand for?
a) PHP: Hyperspeed Performance
b) PHP: Hyperformat Programming
c) PHP: Hypertext Preprocessor
d) PHP: Hyperlink Pages

Page 1 of 31
PHP Introduction

• PHP code is executed on the server.

What is PHP?
• PHP is an acronym for "PHP: Hypertext Preprocessor" [PHP originally stood for
"Personal Home Page"]
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use

PHP is an amazing and popular language!


• It is powerful enough to be at the core of the biggest blogging system on the web
(WordPress)!
• It is deep enough to run large social networks!
• It is also easy enough to be a beginner's first server-side language!

What is a PHP File?


• PHP files can contain text, HTML, CSS, JavaScript, and PHP code
• PHP code is executed on the server, and the result is returned to the browser as plain
HTML
• PHP files have extension ".php"

What Can PHP Do?


• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, and modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data

With PHP you are not limited to output HTML.


You can output images or PDF files.
You can also output any text, such as XHTML and XML.

Why PHP?
• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• PHP is compatible with almost all servers used today (Apache, IIS, etc.)
• PHP supports a wide range of databases

Page 2 of 31
• PHP is free. Download it from the official PHP resource: www.php.net
• PHP is easy to learn and runs efficiently on the server side

Exercise?
What does PHP stand for?
a) PHP: Hyperspeed Performance
b) PHP: Hyperformat Programming
c) PHP: Hypertext Preprocessor
d) PHP: Hyperlink Pages

Page 3 of 31
PHP Installation

What Do I Need?
To start using PHP, you can:
• Find a web host with PHP and MySQL support
• Install a web server on your own PC, and then install PHP and MySQL

Use a Web Host With PHP Support


• If your server has activated support for PHP, you do not need to do anything.
• Just create some .php files, place them in your web directory, and the server will
automatically parse them for you.
• You do not need to compile anything or install any extra tools.
• Because PHP is free, most web hosts offer PHP support.

Set Up PHP on Your Own PC


However, if your server does not support PHP, you must:
• install a web server [Get your own PHP Server]
• install PHP
• install a database, such as MySQL

The official PHP website (PHP.net) has installation instructions for PHP:
http://php.net/manual/en/install.php

PHP Online Compiler / Editor


With w3schools' online PHP compiler, you can edit PHP code, and view the result in your
browser.

Run »
<?php
$txt = "PHP";
echo "I love $txt!";
?>
I love PHP!
Try it Yourself »

PHP Version: To check your php version you can use the phpversion() function:

Example
Display the PHP version: echo phpversion();
Try it Yourself »

Page 4 of 31
PHP Syntax

A PHP script is executed on the server, and the plain HTML result is sent back to the browser.

Basic PHP Syntax


• A PHP script can be placed anywhere in the document.
• A PHP script starts with <?php and ends with?>:
<?php
// PHP code goes here
?>

• The default file extension for PHP files is ".php".


• A PHP file normally contains HTML tags, and some PHP scripting code.

An example of a simple PHP file, with a PHP script that uses a built-in PHP function "echo" to
output the text "Hello World!" on a web page:

Example:
A simple .php file with both HTML code and PHP code:
<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>

Try it Yourself »

Note: PHP statements end with a semicolon (;).

Page 5 of 31
PHP Case Sensitivity
• In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are not case-sensitive.

In the following example, all three echo statements below are equal and legal:
Example
ECHO is the same as echo:
<!DOCTYPE html>
<html>
<body>

<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>

</body>
</html>

Try it Yourself »

Note: However; all variable names are case-sensitive!

• In the following example, only the first statement will display the value of the $color
variable!
• This is because $color, $COLOR, and $coLOR are treated as three different variables:

Example
$COLOR is not same as $color:
<!DOCTYPE html>
<html>
<body>

<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>

Page 6 of 31
</body>
</html>

Try it Yourself »

Page 7 of 31
PHP Comments

• A comment in PHP code is a line that is not executed as a part of the program.
• Its only purpose is to be read by someone who is looking at the code.

Comments can be used to:


• Let others understand your code
• Remind yourself of what you did - Most programmers have experienced coming back to
their own work a year or two later and having to re-figure out what they did. Comments
can remind you of what you were thinking when you wrote the code
• Leave out some parts of your code

PHP supports several ways of commenting:


Example: Syntax for comments in PHP code:
// This is a single-line comment

# This is also a single-line comment

/* This is a
multi-line comment */

Try it Yourself »

Single Line Comments


• Single line comments start with //.
• Any text between // and the end of the line will be ignored (will not be executed).
• You can also use # for single line comments.

The following examples use a single-line comment as an explanation:


Example: A comment before the code:
// Outputs a welcome message:
echo "Welcome Home!";
Try it Yourself »

Example: A comment at the end of a line:


echo "Welcome Home!"; // Outputs a welcome message
Try it Yourself »

• Comments to Ignore Code

Page 8 of 31
• We can use comments to prevent code lines from being executed:

Example: Do not display a welcome message:


// echo "Welcome Home!";
Try it Yourself »

Exercise?
Which one is NOT a legal PHP comment:
a) # comment goes here
b) // comment goes here
c) '' comment goes here
d) /* comment goes here */

Page 9 of 31
Multi-line Comments

• Multi-line comments start with /* and end with */.


• Any text between /* and */ will be ignored.

The following example uses a multi-line comment as an explanation:


Example: Multi-line comment as an explanation:
/*
The next statement will
print a welcome message
*/
echo "Welcome Home!";

Try it Yourself »

• Multi-line Comments to Ignore Code


• We can use multi-line comments to prevent blocks of code from being executed:

Example: Multi-line comment to ignore code:


/*
echo "Welcome to my home!";
echo "Mi casa su casa!";
*/
echo "Hello!";

Try it Yourself »

Comments in the Middle of the Code


• The multi-line comment syntax can also be used to prevent execution of parts inside a code-
line:

Example: The + 15 part will be ignored in the calculation:
$x = 5 /* + 15 */ + 5;
echo $x;

Try it Yourself »

Page 10 of 31
PHP Variables

Variables are "containers" for storing information.

Creating (Declaring) PHP Variables


• In PHP, a variable starts with the $ sign, followed by the name of the variable:

Example: The variable $x will hold the value 5, and the variable $y will hold the value "John".
$x = 5;
$y = "John";
Try it Yourself »

• When you assign a text value to a variable, put quotes around the value.
• Unlike other programming languages, PHP has no command for declaring a variable.
• It is created the moment you first assign a value to it.
• Think of variables as containers for storing data.

PHP Variables
• A variable can have a short name (like $x and $y) or a more descriptive name ($age,
$carname, $total_volume).

Rules for PHP variable names:


• A variable starts with the $ sign, followed by the name of the variable
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-
9, and _ )
• Variable names are case-sensitive ($age and $AGE are two different variables)

Output Variables:
• The PHP echo statement is often used to output data to the screen.

Example: show how to output text and a variable


$txt = "W3Schools.com";
echo "I love $txt!";
Try it Yourself »

Example: Produce the same output as the previous example


$txt = "W3Schools.com";
echo "I love " . $txt . "!";

Page 11 of 31
Try it Yourself »

Example: output the sum of two variables


$x = 5;
$y = 4;
echo $x + $y;
Try it Yourself »

• PHP is a Loosely Typed Language


• In the previous example, we did not have to tell PHP which data type the variable is.
• PHP automatically associates a data type to the variable, depending on its value.
• Since the data types are not set in a strict sense, you can do things like adding a string to an
integer without causing an error.
• In PHP 7, type declarations were added.
• This gives an option to specify the data type expected when declaring a function, and by
enabling the strict requirement, it will throw a "Fatal Error" on a type mismatch.

Variable Types
• PHP has no command for declaring a variable, and the data type depends on the value
of the variable.

Example:
$x = 5; // $x is an integer
$y = "John"; // $y is a string
echo $x;
echo $y;
Try it Yourself »

PHP supports the following data types:


• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource

Get the Type:


• The var_dump() function returns the data type and the value:

Page 12 of 31
Example: To get the data type of a variable, use the var_dump() function.
$x = 5;
var_dump($x);
Try it Yourself »

Example: What var_dump() returns for other data types:


var_dump(5);
var_dump("John");
var_dump(3.14);
var_dump(true);
var_dump([2, 3, 56]);
var_dump(NULL);
Try it Yourself »

Assign String to a Variable


• Assigning a string to a variable is done with the variable name followed by an equal sign
and the string:
• String variables can be declared either by using double or single quotes.

Example:
$x = "John";
echo $x;
Try it Yourself »

Assign Multiple Values


• You can assign the same value to multiple variables in one line:

Example: All three variables get the value "Fruit":


$x = $y = $z = "Fruit";
Try it Yourself »

Exercise?
Which one is NOT a legal PHP variable name:
a) $myVar = 3
b) $my_Var = 3
c) $myvar = 3
d) $my-var = 3

Page 13 of 31
PHP Variables Scope

PHP Variables Scope


• In PHP, variables can be declared anywhere in the script.
• The scope of a variable is the part of the script where the variable can be referenced/used.
• PHP has three different variable scopes:
a) local
b) global
c) static

Global and Local Scope:


• A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function.
• A variable declared within a function has a LOCAL SCOPE and can only be accessed
within that function.
• You can have local variables with the same name in different functions, because local
variables are only recognized by the function in which they are declared.

Example: Variable with global scope:


$x = 5; // global scope

function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

echo "<p>Variable x outside function is: $x</p>";


Try it Yourself »

Example: Variable with local scope:


function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error


echo "<p>Variable x outside function is: $x</p>";
Try it Yourself »

Page 14 of 31
PHP The global Keyword:
• The global keyword is used to access a global variable from within a function.
• To do this, use the global keyword before the variables (inside the function).

Example:
$x = 5;
$y = 10;

function myTest() {
global $x, $y;
$y = $x + $y;
}

myTest();
echo $y; // outputs 15
Try it Yourself »

• PHP also stores all global variables in an array called $GLOBALS[index].


• The index holds the name of the variable.
• This array is also accessible from within functions and can be used to update global
variables directly.

Example:
$x = 5;
$y = 10;

function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}

myTest();
echo $y; // outputs 15
Try it Yourself »

PHP The static Keyword


• Normally, when a function is completed/executed, all of its variables are deleted.
• However, sometimes we want a local variable NOT to be deleted.
• We need it for a further job.
• To do this, use the static keyword when you first declare the variable.

Page 15 of 31
• Then, each time the function is called, that variable will still have the information it
contained from the last time the function was called.
• Note: The variable is still local to the function.

Example:
function myTest() {
static $x = 0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();
Try it Yourself »

Exercise?
Consider the following code:
$name = 'Linus';
function myTest() {
$name = 'Tobias';
}
myTest();
echo $name;
What will be the output?
a) Linus
b) Tobias

// If you wanted the function to modify the global $name, you would need to explicitly declare it
as global inside the function:
$name = 'Linus';
function myTest() {
global $name;
$name = 'Tobias';
}
myTest();
echo $name; // Outputs: Tobias

Page 16 of 31
PHP echo and print Statements

With PHP, there are two basic ways to get output: echo and print.

PHP echo and print Statements


• echo and print are more or less the same.
• They are both used to output data to the screen.
• The differences are small: echo has no return value while print has a return value of 1
so it can be used in expressions.
• echo can take multiple parameters while print can take one argument.
• echo is marginally faster than print.

The PHP echo Statement


• The echo statement can be used with or without parentheses: echo or echo().

Example:
echo "Hello";
//same as:
echo("Hello");
Try it Yourself »

Display Text
• To output text, use the echo command (the text can contain HTML markup):

Example:
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
Try it Yourself »

Display Variables
• To output text and variables use the echo statement:

Example:
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
echo "<h2>$txt1</h2>";
echo "<p>Study PHP at $txt2</p>";
Try it Yourself »

Page 17 of 31
Using Single Quotes:
• Strings are surrounded by quotes, but there is a difference between single and double
quotes in PHP.
• When using double quotes, variables can be inserted to the string as in the example
above.
• When using single quotes, variables have to be inserted using the . operator.

Example:
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";

echo '<h2>' . $txt1 . '</h2>';


echo '<p>Study PHP at ' . $txt2 . '</p>';
Try it Yourself »

The PHP print Statement


• The print statement can be used with or without parentheses: print or print().

Example:
print "Hello";
//same as:
print("Hello");
Try it Yourself »

Display Text
• To output text, use the print command (the text can contain HTML markup):

Example:
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
Try it Yourself »

Display Variables
• To output text and variables with the print statement:

Example:
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";

Page 18 of 31
print "<h2>$txt1</h2>";
print "<p>Study PHP at $txt2</p>";
Try it Yourself »

Using Single Quotes:


• Strings are surrounded by quotes, but there is a difference between single and double
quotes in PHP.
• When using double quotes, variables can be inserted to the string as in the example
above.
• When using single quotes, variables have to be inserted using the . operator.

Example:
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";

print '<h2>' . $txt1 . '</h2>';


print '<p>Study PHP at ' . $txt2 . '</p>';
Try it Yourself »

Exercise?
The two echo statements below will produce the same result:
$name = 'Linus';
echo '<h1>Hello $name</h1>';
echo "<h1>Hello $name</h1>";
a) True
b) False

$name = 'Linus';
echo '<h1>Hello $name</h1>'; // Outputs: <h1>Hello $name</h1>
echo "<h1>Hello $name</h1>"; // Outputs: <h1>Hello Linus</h1>

$name = 'Linus';
echo '<h1>Hello ‘ . $name . ‘</h1>'; // Outputs: <h1>Hello Linus </h1>
echo "<h1>Hello $name</h1>"; // Outputs: <h1>Hello Linus</h1>

Page 19 of 31
PHP Data Types

PHP Data Types


• Variables can store data of different types, and different data types can do different
things.
• PHP supports the following data types:
a) String
b) Integer
c) Float (floating point numbers - also called double)
d) Boolean
e) Array
f) Object
g) NULL
h) Resource

Getting the Data Type


• You can get the data type of any object by using the var_dump() function.

Example: The var_dump() function returns the data type and the value.
$x = 5;
var_dump($x);
Try it Yourself »

PHP String
• A string is a sequence of characters, like "Hello world!".
• A string can be any text inside quotes. You can use single or double quotes.

Example:
$x = "Hello world!";
$y = 'Hello world!';

var_dump($x);
echo "<br>";
var_dump($y);
Try it Yourself »

PHP Integer
• An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.

Page 20 of 31
Rules for integers:
• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or
binary (base 2) notation

Example: $x is an integer. The PHP var_dump() function returns the data type and value:
$x = 5985;
var_dump($x);
Try it Yourself »

PHP Float
• A float (floating point number) is a number with a decimal point or a number in
exponential form.

Example: $x is a float. The PHP var_dump() function returns the data type and value:
$x = 10.365;
var_dump($x);
Try it Yourself »

PHP Boolean
• A Boolean represents two possible states: TRUE or FALSE.
• Booleans are often used in conditional testing.

Example:
$x = true;
var_dump($x);
Try it Yourself »

PHP Array
• An array stores multiple values in one single variable.

Example: In the following example $cars is an array. The PHP var_dump() function returns
the data type and value:
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
Try it Yourself »

Page 21 of 31
PHP Object
• Classes and objects are the two main aspects of object-oriented programming.
• A class is a template for objects, and an object is an instance of a class.
• When the individual objects are created, they inherit all the properties and behaviors
from the class, but each object will have different values for the properties.

Let's assume we have a class named Car that can have properties like model, color, etc.
• We can define variables like $model, $color, and so on, to hold the values of these
properties.
• When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the
properties and behaviors from the class, but each object will have different values for the
properties.
• If you create a __construct() function, PHP will automatically call this function when
you create an object from a class.

Example:
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}

$myCar = new Car("red", "Volvo");


var_dump($myCar);
Try it Yourself »

PHP NULL Value


• Null is a special data type which can have only one value: NULL.
• A variable of data type NULL is a variable that has no value assigned to it.
• If a variable is created without a value, it is automatically assigned a value of NULL.
• Variables can also be emptied by setting the value to NULL:

Page 22 of 31
Example:
$x = "Hello world!";
$x = null;
var_dump($x);
Try it Yourself »

Change Data Type


• If you assign an integer value to a variable, the type will automatically be an integer.
• If you assign a string to the same variable, the type will change to a string:
• If you want to change the data type of an existing variable, but not by changing the
value, you can use casting.
• Casting allows you to change data type on variables.

Example:
$x = 5;
var_dump($x);

$x = "Hello";
var_dump($x);
Try it Yourself »

Example: Casting
$x = 5;
$x = (string) $x;
var_dump($x);
Try it Yourself »

PHP Resource:
• The special resource type is not an actual data type.
• It is the storing of a reference to functions and resources external to PHP.
• A common example of using the resource data type is a database call.

Exercise?
What data type is the $x variable below:
$x = true;
a) Integer
b) Boolean
c) Float
d) String

Page 23 of 31
PHP Strings

A string is a sequence of characters, like "Hello world!".

Strings
• Strings in PHP are surrounded by either double quotation marks, or single quotation
marks.
• There is a big difference between double quotes and single quotes in PHP.
Double quotes process special characters, single quotes does not.

Example:
echo "Hello";
echo 'Hello';
Try it Yourself »

Double or Single Quotes?


• You can use double or single quotes, but you should be aware of the differences between
the two.
• Double quoted strings perform action on special characters.
• e.g. when there is a variable in the string, it returns the value of the variable:
• Single quoted strings does not perform such actions, it returns the string like it was
written, with the variable name.

Example: Double quoted string literals perform operations for special characters:
$x = "John";
echo "Hello $x";
Try it Yourself »

Example: Single quoted string literals return the string as it is:


$x = "John";
echo 'Hello $x';
Try it Yourself »

String Length
• The PHP strlen() function returns the length of a string.

Example: Return the length of the string "Hello world!":


echo strlen("Hello world!");
Try it Yourself »

Page 24 of 31
Word Count
• The PHP str_word_count() function counts the number of words in a string.

Example: Count the number of word in the string "Hello world!":


echo str_word_count("Hello world!");
Try it Yourself »

Search for Text Within a String


• The PHP strpos() function searches for a specific text within a string.
• If a match is found, the function returns the character position of the first match. If no
match is found, it will return FALSE.
• The first character position in a string is 0 (not 1).

Example: Search for the text "world" in the string "Hello world!":
echo strpos("Hello world!", "world");
Try it Yourself »

Exercise?
What will be the output of the following code:
$x = 5;
echo 'The price is $x';

a) The price is 5
b) The price is
c) The price is $x

• If you wanted the variable $x to be parsed and included in the string, you would use
double quotes:
echo "The price is $x"; // Output: The price is 5

Page 25 of 31
PHP - Modify Strings

PHP has a set of built-in functions that you can use to modify strings.

Upper Case
Example: The strtoupper() function returns the string in upper case:
$x = "Hello World!";
echo strtoupper($x);
Try it Yourself »

Lower Case
Example: The strtolower() function returns the string in lower case:
$x = "Hello World!";
echo strtolower($x);
Try it Yourself »

Replace String
• The PHP str_replace() function replaces some characters with some other characters in a
string.

Example: Replace the text "World" with "Dolly":


$x = "Hello World!";
echo str_replace("World", "Dolly", $x);
Try it Yourself »

Reverse a String
• The PHP strrev() function reverses a string.
Example: Reverse the string "Hello World!":
$x = "Hello World!";
echo strrev($x);
Try it Yourself »

Remove Whitespace
• Whitespace is the space before and/or after the actual text, and very often you want to
remove this space.

Example: The trim() removes any whitespace from the beginning or the end:
$x = " Hello World! ";
echo trim($x);
Try it Yourself »

Page 26 of 31
Convert String into Array
• The PHP explode() function splits a string into an array.
• The first parameter of the explode() function represents the "separator".
• The "separator" specifies where to split the string.
• The separator is required.

Example: Split the string into an array. Use the space character as separator:
$x = "Hello World!";
$y = explode(" ", $x);

//Use the print_r() function to display the result:


print_r($y);

/*
Result:
Array ( [0] => Hello [1] => World! )
*/
Try it Yourself »

Exercise?
What is the correct function to return a string as all upper case letters:
a) touppercase()
b) strtoupper()
c) ucase()
d) toupper()

Page 27 of 31
PHP - Concatenate Strings

String Concatenation
• To concatenate, or combine, two strings you can use the . operator:
Example:
$x = "Hello";
$y = "World";
$z = $x . $y;
echo $z;
// The result is HelloWorld, without a space between the two words.
Try it Yourself »
Example: You can add a space character like this:
$x = "Hello";
$y = "World";
$z = $x . " " . $y;
echo $z;
Try it Yourself »
• An easier and better way is by using the power of double quotes.
• By surrounding the two variables in double quotes with a white space between them, the
white space will also be present in the result.
Example
$x = "Hello";
$y = "World";
$z = "$x $y";
echo $z;
Try it Yourself »
Exercise?
What will be the result of $z in the following code example:
$x = 5;
$y = 10;
$z = "$x . $y";
echo $z;
a) 5 . 10
b) 15
c) 5.10

• If you wanted to concatenate $x and $y properly, you would need to use the . operator
outside the string: $z = $x . $y; // $z will be "510"
• Or concatenate explicitly inside the string: $z = "$x" . "$y"; // $z will be "510"

Page 28 of 31
PHP - Slicing Strings

Slicing
• You can return a range of characters by using the substr() function.
• Specify the start index and the number of characters you want to return.
• The first character has index 0.

Example: Start the slice at index 6 and end the slice 5 positions later:
$x = "Hello World!";
echo substr($x, 6, 5);
Try it Yourself »

Slice to the End


• By leaving out the length parameter, the range will go to the end:

Example: Start the slice at index 6 and go all the way to the end:
$x = "Hello World!";
echo substr($x, 6);
Try it Yourself »

Slice From the End


• Use negative indexes to start the slice from the end of the string.
• The last character has index -1.

Example: Get the 3 characters, starting from the "o" in world (index -5):
$x = "Hello World!";
echo substr($x, -5, 3);
Try it Yourself »

Negative Length
• Use negative length to specify how many characters to omit, starting from the end of
the string:

Example:
• From the string "Hi, how are you?", get the characters starting from index 5, and continue
until you reach the 3. character from the end (index -3).
• Should end up with "ow are y":
$x = "Hi, how are you?";
echo substr($x, 5, -3);
Try it Yourself »

Page 29 of 31
Exercise?
What will be the result of the following slice:
$x = "Hello World!";
echo substr($x, 3, 2);
a) ll
b) el
c) lo

Page 30 of 31
PHP - Escape Characters

Escape Character
• To insert characters that are illegal in a string, use an escape character.

• An escape character is a backslash \ followed by the character you want to insert.


• An example of an illegal character is a double quote inside a string that is surrounded by
double quotes:

Example:
$x = "We are the so-called "Vikings" from the north."; \\ PHP Parse Error
Try it Yourself »

• To fix this problem, use the escape character \":


$x = "We are the so-called \"Vikings\" from the north.";
Try it Yourself »

Escape Characters: Other escape characters used in PHP:

Code Result Try it

\' Single Quote Try it »

\" Double Quote Try it »

\$ PHP variables Try it »

\n New Line Try it »

\r Carriage Return Try it »

\t Tab Try it »

\f Form Feed

\ooo Octal value Try it »

\xhh Hex value Try it »

Page 31 of 31

You might also like