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

2. PHP Variables_ Data Types and constants

Uploaded by

sachin248124
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

2. PHP Variables_ Data Types and constants

Uploaded by

sachin248124
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 68

PHP VARIABLES, DATA

TYPES AND
CONSTANTS
PHP Variables
• Variables are used to store data, like string of text,
numbers, etc. Variable values can change over the course
of a script. Here're some important things to know about
variables:

• In PHP variable can be declared as: $var_name = value;


Creating (Declaring) PHP Variables

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


name of the variable:

<?php
$x = 5;
$y = "John";
echo $x;
echo "<br>";
echo $y;
?>
Naming Conventions for PHP Variables
These are the following rules for naming a PHP variable:

• All variables in PHP start with a $ 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 in PHP can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _).
• A variable name cannot contain spaces.
• PHP variables are case-sensitive, so $name and $NAME
both are treated as different variable.
Case Sensitivity in PHP

In PHP, keywords (e.g. if, else, while, echo, etc.), classes,


functions, and user-defined functions are not case-
sensitive.

<?php

ECHO "Hello World!<br>";


echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
• Variable names in PHP are case-sensitive.

<!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>
Difference between double and single quotes
• When using double quotes, variables can be inserted to
the string as in the example below:-
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
echo "<h2>$txt1</h2>";
echo "<p>Study PHP at $txt2</p>";

• When using single quotes, variables have to be inserted


using the . operator, like this:
Single Quote example
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";

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


echo '<p>Study PHP at ' . $txt2 . '</p>';
Single quotes will print the variable name, not the value:

• <?php
$color = "red";
print "Roses are $color";
print "<br>";
print 'Roses are’. $color;
?>

To access a variable within single quotes in PHP, you should


use the concatenation operator
Adding Two Numbers in PHP
<?php
$a=10.8;
$b=20.9;
echo "The addition of two numbers is". $a+
$b."<br>";
echo "The subtraction of two numbers is".
$a-$b."<br>";
echo "The multiplication of two numbers
is". $a*$b;
?>
PHP is a Loosely Typed Language

• In the example above, notice that 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 8, adding an integer and a string directly using the
+ operator is more strictly handled than in previous
versions, leading to an error or warning. PHP 8 introduced
stricter type handling, which is why your code might not
be working as expected.
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:

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


A variable declared within a function has a
LOCAL SCOPE and can only be accessed within
that function:

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>";
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):
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
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:
Use of Static Keyword
function myTest() {
static $x = 0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();
Data Types in PHP
• PHP supports total eight primitive data types:
- Integer
- Float
- String
- Boolean
- Array
- Object
- Resource
- NULL
Get the
Type
.

• To get the data type of a variable, use


the var_dump() function

<?php
$x=8;
$y=6.8;
$z="Strings";
var_dump($x);
var_dump($y);
var_dump($z);
?>
Get the Data Type
<!DOCTYPE html>
<html>
<body>
<pre>
<?php
var_dump(5);
var_dump("John");
var_dump(3.14);
var_dump(true);
var_dump([2, 3, 56]);
var_dump(NULL);
?>
</pre>
</body>
</html>
PHP Numbers

There are three main numeric types in PHP:

• Integer
• Float
• Number Strings
Data types used for numbers:
• In addition, PHP has two more data types used for
numbers:

• Infinity
• NaN
Example of Numbers in PHP
<!DOCTYPE html>
<html>
<body>

<?php
$a = 5;
$b = 5.34;
$c = "25";

var_dump($a);
echo "<br>";
var_dump($b);
echo "<br>";
var_dump($c);
?>

</body>
</html>
Example of Numbers in PHP
<?php
$x=9;
$y=8.9;
$z="76";
echo "The data type of x
is".var_dump($x)."<br>";
echo "The data type of y
is".var_dump($y)."<br>";
echo "The data type of z
is".var_dump($z)."<br>";
?>
PHP Integers
• Integers are whole numbers, without a decimal point (..., -
2, -1, 0, 1, 2, ...).

• An integer data type is a non-decimal number between


-2,147,483,648 and 2,147,483,64 .
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 three formats: decimal (base
10), hexadecimal (base 16 - prefixed with 0x), octal (base
8 - prefixed with 0) or binary (base 2 - prefixed with 0b)
• PHP_INT_MAX - The largest integer supported
• PHP_INT_MIN - The smallest integer supported
• PHP_INT_SIZE - The size of an integer in bytes
The max and min value of INTEGER
<?php
echo "The maximum integer value in PHP is "
. PHP_INT_MAX . "<br>";
echo "The minimum integer value in PHP is "
. PHP_INT_MIN . "<br>";
echo "The SIZE of x integer value in PHP is
" . PHP_INT_SIZE . "<br>"; //The integer
size in bytes.

?>
Check if the type of a variable is integer
<!DOCTYPE html>
<html>
<body>

<?php
// Check if the type of a variable is integer
$x = 5985;
var_dump(is_int($x));

echo "<br>";

// Check again...
$x = 59.85;
var_dump(is_int($x));
?>

</body>
</html>
SIZE OF AN INTEGER
<?php
$x=5;
if(is_int($x)){
echo $x."is an integer";
ECHO "<BR>";
}
echo "The size of the integer x is".
PHP_INT_SIZE;//On most 64-bit systems,
PHP_INT_SIZE will return 8, meaning that an
integer is 8 bytes
?>
PHP Floating Point Numbers or Doubles
• Floating point numbers (also known as "floats", "doubles",
or "real numbers") are decimal or fractional numbers
Check if the type of a variable is float
<!DOCTYPE html>
<html>
<body>

<?php
// Check if the type of a variable is float
$x = 10.365;
var_dump(is_float($x));
?>

</body>
</html>
Check if a numeric value is finite or infinite

<!DOCTYPE html>
<html>
<body>

<?php
// Check if a numeric value is finite or infinite
$x = 1.9e411;
var_dump($x);
?>

</body>
</html>
Check if the variable is numeric
<!DOCTYPE html>
<html>
<body>
<?php
// Check if the variable is numeric
$x = 5985;
var_dump(is_numeric($x));
echo "<br>";
$x = "5985";
var_dump(is_numeric($x));
echo "<br>";
$x = "59.85" + 100;
var_dump(is_numeric($x));
echo "<br>";
$x = "Hello";
var_dump(is_numeric($x));
?>
</body>
</html>
INFINTE and NAN
<?php
// Demonstrating Positive Infinity
$positive_infinity = 1.0 / 0.0; // Dividing by zero results in
infinity
echo "Positive Infinity: $positive_infinity\n"; // Outputs:
Positive Infinity: INF
// Demonstrating Negative Infinity
$negative_infinity = -1.0 / 0.0; // Negative number divided by
zero results in negative infinity
echo "Negative Infinity: $negative_infinity\n"; // Outputs:
Negative Infinity: -INF
?>
Fatal error: Uncaught DivisionByZeroError: Division by zero in C:\
xampp\htdocs\PHP-Practice\13Infandnan.php:3 Stack trace: #0
{main} thrown in C:\xampp\htdocs\PHP-Practice\13Infandnan.php
on line 3

The error you're encountering, Fatal error: Uncaught


DivisionByZeroError, occurs because PHP 7 introduced
stricter error handling for division by zero. In earlier
versions, dividing by zero would return INF or -INF, but
starting with PHP 7, it throws a DivisionByZeroError
instead.To avoid this error and achieve the desired output,
you can modify your code to explicitly handle division by
zero or use INF directly.
PHP Casting Strings and Floats to Integers

// Cast float to int


$x = 23465.768;
$int_cast = (int)$x;
echo $int_cast;
echo "<br>";
// Cast string to int
$x = "23465.768";
$int_cast = (int)$x;
echo $int_cast;
PHP Math
• PHP has a set of math functions that allows you to perform
mathematical tasks on numbers.

PHP pi() Function
• The pi() function returns the value of PI:

<!DOCTYPE html>
<html>
<body>

<?php
echo(pi());
?>

</body>
</html>
PHP min() and max() Functions

• The min() and max() functions can be used to find the


lowest or highest value in a list of arguments

<!DOCTYPE html>
<html>
<body>
<?php
echo(min(0, 150, 30, 20, -8, -200) . "<br>");
echo(max(0, 150, 30, 20, -8, -200));
?>
</body>
</html>
PHP abs() Function

• The abs() function returns the absolute (positive) value of a


number:
<!DOCTYPE html>
<html>
<body>

<?php
echo(abs(-6.7));
?>

</body>
</html>
PHP sqrt() Function

• The sqrt() function returns the square root of a number:

<!DOCTYPE html>
<html>
<body>

<?php
echo(sqrt(64) . "<br>");
echo(sqrt(0) . "<br>");
echo(sqrt(1) . "<br>");
echo(sqrt(9));
?>

</body>
</html>
PHP round() Function
The round() function rounds a floating-point number to its nearest integer:

<!DOCTYPE html>
<html>
<body>
<?php
echo(round(0.60) . "<br>");
echo(round(0.50) . "<br>");
echo(round(0.49) . "<br>");
echo(round(-4.40) . "<br>");
echo(round(-4.60));
?>
</body>
</html>
Random Numbers

• The rand() function generates a random number:


<!DOCTYPE html>
<html>
<body>
<?php
echo(rand());
?>
</body>
</html>
PHP Strings
• Strings are sequences of characters, where every
character is the same as a byte.

• A string can hold letters, numbers, and special characters


and it can be as large as up to 2GB.

• The simplest way to specify a string is to enclose it in


single quotes (e.g. 'Hello world!'), however you can also
use double quotes ("Hello world!").
String Functions
$name = "Amit is a good boy";
echo $name;
echo "<br>";
echo "The length of " . "my string is " . strlen($name);
echo "<br>";
echo str_word_count($name);
echo "<br>";
echo strrev($name); //revere the string
echo "<br>";
echo strpos($name, “Amit");
echo "<br>";
echo str_replace(“Amit", "Rohan", $name);
echo "<br>";
echo str_repeat($name, 4);
echo "<br>";
echo "<pre>";
echo rtrim(" this is a good boy ");
echo "<br>";
echo ltrim(" this is a good boy ");
PHP Booleans
• Booleans are like a switch it has only two possible values
either 1 (true) or 0 (false).
PHP Booleans
<!DOCTYPE html>
<html>
<body>
<?php
$x = true;
var_dump($x);
?>
</body>
</html>
PHP Arrays
• An array is a variable that can hold more than one value
at a time.

• It is useful to aggregate a series of related items together,


for example a set of country or city names.

• An array is formally defined as an indexed collection of


data values.

• Each index (also known as the key) of an array is unique


and references a corresponding value.
Arrays
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
</body>
</html>
Traversing the Arrays
<?php
$x=["Zen", "Maruti","Fiat"];
echo $x[2];
for ($i=0; $i<(sizeof($x)); $i++){
// The count() function is a built-in PHP function used to
count the number of elements in an array. It returns the
total count of elements within the array.
echo $x[$i];
echo "<br>";
}
?>
PHP Object
• An object is a data type that not only allows storing data
but also information on, how to process that data.
• An object is a specific instance of a class which serve as
templates for objects.
• Objects are created based on this template via the new
keyword.
• Every object has properties and methods corresponding
to those of its parent class.
• Every object instance is completely independent, with its
own properties and methods, and can thus be
manipulated independently of other objects of the same
class.
<?php
// Define a class named Car
class Car {
public $color;

public function setColor($color) {


$this->color = $color; // $this refers to the current object
}

public function getColor() {


return $this->color;
}
}

// Create an object (instance) of the class Car


$myCar = new Car();

// Set the color of the car


$myCar->setColor("Red");

// Get and display the color of the car


PHP Null
• The special NULL value is used to represent empty
variables in PHP.

• A variable of type NULL is a variable without any data.


NULL is the only possible value of type null.
<?php
// Declare a variable and assign it a value
$name = "Alice";

// Output the value of the variable


echo "Name: $name\n"; // Outputs: Name: Alice

// Set the variable to null


$name = null;

// Check if the variable is null


if (is_null($name)) {
echo "The variable 'name' is null now.\n"; // Outputs: The variable 'name' is null
now.
}

// Trying to echo a null variable will produce no output


echo "Name: $name\n"; // Outputs: Name:
?>
PHP Resources
• A resource is a special variable, holding a reference to an
external resource.

• Resource variables typically hold special handlers to


opened files and database connections.
PHP Resources
$file = fopen('example.txt', 'r’);
if ($file)
{
//Use the file handle for reading $contents = fread($file,
filesize('example.txt'));
fclose($file); // Close the file handle when done
}
PHP Resources
$conn = mysqli_connect('localhost', 'username', 'password',
'database’);
if ($conn) {
// Use the connection for queries $result =
mysqli_query($conn, 'SELECT * FROM users');
mysqli_close($conn); // Close the connection when done}
Constants
• A constant is a name or an identifier for a fixed value.

• Constant are like variables, except that once they are


defined, they cannot be undefined or changed.

• PHP constants can be defined by 2 ways:


- Using define() function
- Using const keyword
Constants(contd.)
• PHP constant: define() - Use the define() function to
create a constant. It defines constant at run time.

define(name, value)

- name: It specifies the constant name.


- value: It specifies the constant value.
Constants(contd.)
<?php
// case-sensitive constant name
define("WISHES", "Good Evening");
echo WISHES;
?>

OUTPUT:
Good Evening
Constants(contd.)
• PHP constant: const keyword - PHP introduced a
keyword const to create a constant. The const keyword
defines constants at compile time. It is a language
construct, not a function. The constant defined using
const keyword are case-sensitive.

<?php
const WISHES="Good day";
echo WISHES;
?>
OUTPUT:
Good day
Constants(contd.)
• Constant() function - There is another way to print the
value of constants using constant() function.

• The syntax for the following constant function:

constant (name)
Constants(contd.)
<?php
define("WISHES", "Good Evening");
echo WISHES. "<br>";
echo constant("WISHES"); //print the value of the
constant
//both are similar
?>

OUTPUT:
Good Evening
Good Evening
Constants(contd.)
• PHP Constant Arrays - In PHP, you can create an Array
constant using the define() function.

<?php
define("courses", [
"PHP",
"HTML",
"CSS"
]);
echo courses[0];
?>
OUTPUT:
PHP
Constants(contd.)
• PHP Constant Arrays - In PHP, you can also create an
Array constant using const keyword.

<?php
const WISHES=array("PHP",
"HTML",
"CSS");
echo WISHES[0];
?>

OUTPUT:
PHP
Constants(contd.)
• Constants are Global - Constants are automatically
global and can be used across the entire script.

<?php
define("WISHES", "Good Evening");

function test() {
echo WISHES;
}
test();
?>

OUTPUT:
Good Evening
Example of Constants
• <?php

• // Defining constants using the define() function


• define("PI", 3.14159265359);
• define("GRAVITY", 9.81);

• // Using constants
• $radius = 5;
• $circumference = 2 * PI * $radius;

• echo "Example 1: Circumference of a circle with radius $radius is


$circumference\n"; // Output: 31.4159265359
• echo "Gravity on Earth is " . GRAVITY . " m/s²\n"; // Output: 9.81

• ?>
Defining Color Constants
• <?php

• // Defining an array constant


• define("COLORS", [
• "RED" => "#FF0000",
• "GREEN" => "#00FF00",
• "BLUE" => "#0000FF"
• ]);

• echo "Example 4: Red color code is " . COLORS["RED"] . "\n"; // Output:


#FF0000
• echo "Green color code is " . COLORS["GREEN"] . "\n"; // Output: #00FF00
• echo "Blue color code is " . COLORS["BLUE"] . "\n"; // Output: #0000FF

• ?>

You might also like