0% found this document useful (0 votes)
2 views23 pages

PHP Baiscs

The document provides an overview of PHP, a widely-used open-source scripting language essential for web development. It covers basic PHP syntax, variable declaration, data types, operators, and conditional statements, emphasizing PHP's versatility and ease of use. Additionally, it highlights PHP's capabilities in generating dynamic content and interacting with databases.

Uploaded by

kg7969008
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)
2 views23 pages

PHP Baiscs

The document provides an overview of PHP, a widely-used open-source scripting language essential for web development. It covers basic PHP syntax, variable declaration, data types, operators, and conditional statements, emphasizing PHP's versatility and ease of use. Additionally, it highlights PHP's capabilities in generating dynamic content and interacting with databases.

Uploaded by

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

PHP Full Stack Development

What You Should Already Know


Before you continue you should have a basic understanding of the following:

●​ HTML
●​ CSS
●​ JavaScript

What is PHP?

●​ PHP is an acronym for "PHP: Hypertext Preprocessor"


●​ 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, 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
●​ 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

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

Below, we have 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:

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>

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

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 example below, all three echo statements below are equal and legal:

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>
Note: However; all variable names are case-sensitive!

Look at the example below; 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:

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

?>

</body>

</html>

PHP Variables

Creating (Declaring) PHP Variables

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

$id = 5;

$name = "alfiya";
In the example above, the variable $id will hold the value 5, and the variable
$name will hold the value "John".

Note: When you assign a text value to a variable, put quotes around the
value.

Note: Unlike other programming languages, PHP has no command for


declaring a variable. It is created the moment you first assign a value to it.

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

Rules for PHP variables:

●​ 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)

Remember that PHP variable names are case-sensitive!

Output Variables

The PHP echo statement is often used to output data to the screen.

The following example will show how to output text and a variable:

Example

$txt = "PHP";
echo "I love $txt!";

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:

●​ local
●​ global
●​ static

Global and Local Scope

A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function:

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

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


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 (although such usage is rare) 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().

echo "Hello";
//same as:
echo("Hello");

The following example shows how to output text with the echo command
(notice that the text can contain HTML markup):

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.";
PHP Data Types

Variables can store data of different types, and different data types can do
different things.

PHP supports the following data types:

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

PHP Constants

A constant is an identifier (name) for a simple value. The value cannot be


changed during the script.

A valid constant name starts with a letter or underscore (no $ sign before the
constant name).

Note: Unlike variables, constants are automatically global across the entire
script.

Create a PHP Constant

To create a constant, use the define() function.

Syntax

define(name, value);

Parameters:

●​ name: Specifies the name of the constant


●​ value: Specifies the value of the constant

Create a constant with a case-sensitive name:


define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;

PHP Operators

Operators are used to perform operations on variables and values.

PHP divides the operators in the following groups:

●​ Arithmetic operators
●​ Assignment operators
●​ Comparison operators
●​ Increment/Decrement operators
●​ Logical operators
●​ String operators
●​ Array operators
●​ Conditional assignment operators

PHP Arithmetic Operators

The PHP arithmetic operators are used with numeric values to perform
common arithmetical operations, such as addition, subtraction, multiplication
etc.

Operator Name Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and


$y

* Multiplication $x * $y Product of $x and $y


/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x
divided by $y

** Exponentiation $x ** $y Result of raising $x to


the $y'th power

PHP Assignment Operators

The PHP assignment operators are used with numeric values to write a value
to a variable.

The basic assignment operator in PHP is "=". It means that the left operand
gets set to the value of the assignment expression on the right.

Assignm Same as... Description


ent

x=y x=y The left operand gets set to the


value of the expression on the
right

x += y x=x+y Addition

x -= y x=x-y Subtraction

x *= y x=x*y Multiplication
x /= y x=x/y Division

x %= y x=x%y Modulus

PHP Comparison Operators

The PHP comparison operators are used to compare two values (number or
string):

Operator Name Example Result

== Equal $x == $y Returns true if $x


is equal to $y

=== Identical $x === $y Returns true if $x


is equal to $y, and
they are of the
same type

!= Not equal $x != $y Returns true if $x


is not equal to $y

<> Not equal $x <> $y Returns true if $x


is not equal to $y

!== Not identical $x !== $y Returns true if $x


is not equal to $y,
or they are not of
the same type
> Greater than $x > $y Returns true if $x
is greater than $y

< Less than $x < $y Returns true if $x


is less than $y

>= Greater than $x >= $y Returns true if $x


or equal to is greater than or
equal to $y

<= Less than or $x <= $y Returns true if $x


equal to is less than or
equal to $y

<=> Spaceship $x <=> $y Returns an


integer less than,
equal to, or
greater than zero,
depending on if
$x is less than,
equal to, or
greater than $y.
Introduced in PHP
7.

PHP Increment / Decrement Operators

The PHP increment operators are used to increment a variable's value.

The PHP decrement operators are used to decrement a variable's value.


Operator Same as... Description

++$x Pre-increment Increments $x by one, then


returns $x

$x++ Post-incremen Returns $x, then increments $x by


t one

--$x Pre-decrement Decrements $x by one, then


returns $x

$x-- Post-decremen Returns $x, then decrements $x by


t one

PHP Logical Operators

The PHP logical operators are used to combine conditional statements.

Operator Name Example Result

and And $x and $y True if both $x


and $y are true

or Or $x or $y True if either $x
or $y is true
xor Xor $x xor $y True if either $x
or $y is true, but
not both

&& And $x && $y True if both $x


and $y are true

|| Or $x || $y True if either $x
or $y is true

! Not !$x True if $x is not


true

PHP String Operators

PHP has two operators that are specially designed for strings.

Operator Name Example Result

. Concatenation $txt1 . $txt2 Concatenation of


$txt1 and $txt2

.= Concatenation $txt1 .= $txt2 Appends $txt2 to


assignment $txt1

PHP Array Operators

The PHP array operators are used to compare arrays.


Operator Name Example Result

+ Union $x + $y Union of $x and


$y

== Equality $x == $y Returns true if $x


and $y have the
same key/value
pairs

=== Identity $x === $y Returns true if $x


and $y have the
same key/value
pairs in the same
order and of the
same types

!= Inequality $x != $y Returns true if $x


is not equal to $y

<> Inequality $x <> $y Returns true if $x


is not equal to $y

!== Non-identity $x !== $y Returns true if $x


is not identical to
$y

PHP Conditional Assignment Operators

The PHP conditional assignment operators are used to set a value depending
on conditions:
Operator Name Example Result

?: Ternary $x = expr1 ? Returns the


expr2 : expr3 value of $x.

The value of $x
is expr2 if expr1
= TRUE.

The value of $x
is expr3 if expr1
= FALSE

?? Null coalescing $x = expr1 ?? Returns the


expr2 value of $x.

The value of $x
is expr1 if expr1
exists, and is not
NULL.

If expr1 does
not exist, or is
NULL, the value
of $x is expr2.

Introduced in
PHP 7

PHP Conditional Statements

Very often when you write code, you want to perform different actions for
different conditions. You can use conditional statements in your code to do
this.

In PHP we have the following conditional statements:

●​ if statement - executes some code if one condition is true


●​ if...else statement - executes some code if a condition is true and
another code if that condition is false
●​ if...elseif...else statement - executes different codes for more
than two conditions
●​ switch statement - selects one of many blocks of code to be executed

PHP - The if Statement

The if statement executes some code if one condition is true.

Syntax

if (condition) {

// code to be executed if condition is true;

Output "Have a good day!" if 5 is larger than 3:

if (5 > 3) {

echo "Have a good day!";

PHP - The if...else Statement

The if...else statement executes some code if a condition is true and


another code if that condition is false.

Syntax

if (condition) {

// code to be executed if condition is true;

} else {

// code to be executed if condition is false;

}
Output "Have a good day!" if the current time is less than 20, and "Have a good
night!" otherwise:

$t = date("H");

if ($t < "20") {

echo "Have a good day!";

} else {

echo "Have a good night!";

PHP - The if...elseif...else Statement

Output "Have a good morning!" if the current time is less than 10, and "Have
a good day!" if the current time is less than 20. Otherwise it will output
"Have a good night!":

$t = date("H");

if ($t < "10") {

echo "Have a good morning!";

} elseif ($t < "20") {

echo "Have a good day!";

} else {

echo "Have a good night!";

Nested If

You can have if statements inside if statements, this is called nested if


statements.
An if inside an if:

$a = 13;

if ($a > 10) {

echo "Above 10";

if ($a > 20) {

echo " and also above 20";

} else {

echo " but not above 20";

PHP Loops

Often when you write code, you want the same block of code to run over and
over again a certain number of times. So, instead of adding several almost
equal code-lines in a script, we can use loops.

Loops are used to execute the same block of code again and again, as long
as a certain condition is true.

In PHP, we have the following loop types:

●​ while - loops through a block of code as long as the specified


condition is true
●​ do...while - loops through a block of code once, and then repeats
the loop as long as the specified condition is true
●​ for - loops through a block of code a specified number of times
●​ foreach - loops through a block of code for each element in an array

The PHP while Loop

The while loop executes a block of code as long as the specified condition is
true.
Print $i as long as $i is less than 6:

$i = 1;

while ($i < 6) {

echo $i;

$i++;

The PHP do...while Loop

The do...while loop will always execute the block of code at least once, it
will then check the condition, and repeat the loop while the specified
condition is true.

Print $i as long as $i is less than 6:

$i = 1;

do {

echo $i;

$i++;

} while ($i < 6);

The PHP for Loop

The for loop is used when you know how many times the script should run.

This is how it works:

●​ expression1 is evaluated once


●​ expression2 is evaluated before each iteration
●​ expression3 is evaluated after each iteration

Print the numbers from 0 to 10:

for ($x = 0; $x <= 10; $x++) {

echo "The number is: $x <br>";

1.​ The first expression, $x = 0;, is evaluated once and sets a counter to
0.
2.​ The second expression, $x <= 10;, is evaluated before each iteration,
and the code block is only executed if this expression evaluates to
true. In this example the expression is true as long as $x is less than,
or equal to, 10.
3.​ The third expression, $x++;, is evaluated after each iteration, and in
this example, the expression increases the value of $x by one at each
iteration.

Break in For loop

The break statement can be used to jump out of a for loop.

Jump out of the loop when $x is 4:

for ($x = 0; $x < 10; $x++) {

if ($x == 4) {

break;

echo "The number is: $x <br>";

}
Continue in For Loops

The continue statement stops the current iteration in the for loop and
continue with the next.

Move to next iteration if $x = 4:

for ($x = 0; $x < 10; $x++) {

if ($x == 4) {

continue;

echo "The number is: $x <br>";

You might also like