0% found this document useful (0 votes)
5 views40 pages

PHP Variables and Data Types Guide

Chapter Two covers the basics of PHP, including variables, data types, and their scopes. It explains how to create and use variables, constants, and functions, as well as conditional statements and loops. Additionally, it discusses operators and how to pass arguments by reference in functions.

Uploaded by

Abdul Sg
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)
5 views40 pages

PHP Variables and Data Types Guide

Chapter Two covers the basics of PHP, including variables, data types, and their scopes. It explains how to create and use variables, constants, and functions, as well as conditional statements and loops. Additionally, it discusses operators and how to pass arguments by reference in functions.

Uploaded by

Abdul Sg
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

CHAPTER TWO

PHP BASICS

1
VARIABLES AND DATA TYPES
PHP Variables
 Variables are "containers" for storing information.

▪ A variable can have a short name (like $x and $y) or a more descriptive name ($age, $carname, $total_volume).
 Rules for PHP variables
o A variable starts with the $ sign, followed by the name of the variable
o A variable name must start with a letter or the underscore character
o A variable name cannot start with a number
o A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

o Variable names are case-sensitive ($age and $AGE are two different variables)

2
CONT'D
 Example:

<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
 PHP is a Loosely Typed Language

 PHP automatically associates a data type to the variable, depending on its value.

3
CONT'D
Accessing variable values:
The PHP echo statement is often used to output data to the screen.
 The following example will produce the same output

4
CONT'D

The following example will output the sum of two variables:

5
PHP COMMENT

 Use // or # to add single line comment

 Use /* .. */ to add multiple line comment

 Example;

6
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 and Static

 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

7
PHP VARIABLES SCOPE EXAMPLE

8
PHP THE GLOBAL KEYWORD
 A global variable can be accessed from within a function using either global keywork or global
array

$x = 5; $y = 10;
function
myTest() {
global $x, $y;
$y = $x + $y; }
myTest();
echo $y;
outputs 15

9
PHP THE GLOBAL KEYWORD
▪ 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.

The previous example can be rewritten like this:

$x = 5; $y = 10;
function myTest() {
$GLOBALS['y'] =
$GLOBALS['x'] +
$GLOBALS['y']; }
myTest();
echo $y;
outputs 15

10
EXERCISE

<?php
$name = 'Linus';
<?php
$name = 'Linus’;
function myTest() {
$name = 'Tobias'; function myTest() {
global $name;
}
$name = 'Tobias';
myTest(); }
echo $name; myTest();
?> echo $name;
?>
What will be the
output?
11
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:

Output
0
1
2

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

13
CONT'D

 Parameters:

 name: Specifies the name of the constant

 value: Specifies the value of the constant

Example

Create a constant with a case-sensitive name:

define("GREETING", "Welcome to [Link]!",true);

echo GREETING;

14
PHP CONST KEYWORD
You can also create a constant by using the const keyword.

Example
:
Create a case-sensitive constant with the const keyword
const MYCAR = "Volvo"; echo MYCAR;

const vs. define()


•const cannot be created inside another block scope, like
inside a function or inside an if statement.
•define() can be created inside another block scope.

15
PHP DATA TYPES

Data Type Description Example

String A sequence of characters, like "Hello world!" $y = 'Hello world!';


echo "<br>";
echo $y;

Integer A non-decimal number between - $x = 5985;


2,147,483,648 and 2,147,483,647 var_dump($x);

Float A number with a decimal point or a number in $x = 10.365;


exponential form var_dump($x);

Boolean Represents two possible states: TRUE or $x = true; or $y = false;


FALSE

16
CONT'D
Array Stores multiple values in one single $cars = array("Volvo","BMW","Toyota");
variable var_dump($cars);

Objects Instances of user-defined classes that class bike {


can store both values and functions. function model() {
They must be explicitly declared. $model_name = "Royal Enfield";
echo "Bike Model: " .$model_name; }
}
$obj = new bike();
$obj -> model();

17
CONT'D

Resources Are not the exact data type in PHP. For example - a database call. It is an
Basically, these are used to store external resource
some function calls or references to
external PHP resources.

Null is a special data type that has only $nl = NULL;


one value: NULL

18
PHP CONDITIONAL STATEMENTS

if Statements

 The if statement executes some


code if one condition is true.
 Syntax

if (condition) {
code to be executed if condition is
true;
}
 Example

19
PHP IF...ELSE STATEMENTS
 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;

 Example

20
PHP - THE IF...ELSEIF...ELSE STATEMENT
 The if...elseif...else statement executes different codes for more than two conditions.

 Syntax

 if (condition) {

 code to be executed if this condition is true;

 } elseif (condition) {

 // code to be executed if first condition is false and this condition is true;

 } else {

 // code to be executed if all conditions are false;

 }

Example
21
PHP SWITCH STATEMENT
 Use the switch statement to select one of many blocks of
code to be executed
 Syntax:
switch (expression) {
case label1:
//code block
break;
case label2:
//code block;
break;
case label3:
//code block
break;
default:
//code block
22
}
PHP 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

23
PHP WHILE LOOP

 The while loop executes a block of code as long as the specified condition is true.

 Syntax:

 while (condition is true) {

code to be executed;

 Example:

24
PHP DO WHILE LOOP
 The do...while loop - Loops through a block of code once,and then repeats the loop as long as the specified
condition is true.

 Syntax

 do {

code to be executed;

} while (condition is true);

 Example:

25
PHP FOR LOOP

 The for loop - Loops through a block of code a specified number of times.

 Syntax:
for (init counter; test counter; increment counter) {

code to be executed for each iteration;

 Example:

26
PHP FOREACH LOOP
 The foreach loop - Loops through a block of code for each element in an array or each property in an object.

 Syntax

 foreach ($array as $value) {

code to be executed;

Example:

27
PHP BREAK AND CONTINUE
 PHP Break can be used to "jump out" of a switch statement or a loop

 PHP Continue continue statement breaks one iteration

(in the loop), if a specified condition occurs, and continues with the next iteration in the loop

28
Operator Name Example Result

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

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


 Arithmetic Operators $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

29
Assignment Same As ... Description

CONT'D x=y x=y The left operand gets set

 Assignment Operators 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

30
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y

CONT'D === 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

 Comparison Operators
<> 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 or equal to $x >= $y Returns true if $x is greater than or equal to $y

<= Less than or equal to $x =< $y Returns true if $x 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.

31
Operator Name Description
CONT'D
Pre- Increments $x by one, then returns
++$x
 Increment / Decrement increment $x
Operators
Post- Returns $x, then increments $x
$x++
increment by one

Decrements $x by one, then returns


--$x Pre- decrement
$x

Returns $x, then decrements $x


$x-- Post- decrement
by one

32
CONT'D
Operator Name Description

 Logical Operators and And True if both conditions are true

&& And True if both conditions are true

or Or True if either condition is true

|| Or True if either condition is true

xor Xor True if either condition is true, but not both

! Not True if condition is not true

33
PHP FUNCTIONS
 A function is a block of statements that can be used repeatedly in a program.

 A function will not execute automatically when a page loads.

 A function will be executed by a call to the function.

 PHP has more than 1000 built-in functions, and in addition you can create your own custom functions.

 A user-defined function declaration starts with the keyword function, followed by the name of the function.

 Example:

function myMessage() {

echo "Hello world!";

}
34
CONT'D

 Call a Function
 To call the function, just write its name followed by parentheses ().
 Example:

function myMessage() {

echo "Hello world!";

myMessage(); // call the function

35
PHP FUNCTION ARGUMENTS

 Information can be passed to functions through arguments. An argument is just like a variable.

 Arguments are specified after the function name, inside the parentheses.

 You can add as many arguments as you want, just separate them with a comma.

 Example:

36
PHP FUNCTIONS - RETURNING VALUES

 To let a function return a value, use the return statement.

 Example:

37
AMPERSAND OPERATOR(&) - PASSING ARGUMENTS BY REFERENCE
• In PHP, the & (ampersand) sign is used to create a reference to a variable rather than a copy
of its value.
• This means that when you assign a variable to another variable using &, both variables will
point to the same data in memory. Changes made to one variable will affect the other.

Example:

38
PASSING ARGUMENTS BY REFERENCE
 In PHP, arguments are usually passed by value, which means that a copy of the value is used in the function and the variable that was passed
into the function cannot be changed.

 When a function argument is passed by reference, changes to the argument also change the variable that was passed in.

 To turn a function argument into a reference, the & operator is used.

 Example:

 function add_five(&$value) {

 $value += 5;

 }

 $num = 2;

 add_five($num);

 echo $num;

39
CONT'D

~~~~~END OF CHAPTER 2 ~~~~~

40

You might also like