0% found this document useful (0 votes)
11 views20 pages

unit 2 text and number

Chapter 2 of the document covers working with text and numbers in PHP, including variables, data types, and built-in string functions. It explains the rules for PHP variables, the concept of loosely typed languages, and details various data types such as strings, integers, floats, and arrays. Additionally, it discusses operators in PHP, including arithmetic, assignment, and comparison operators.

Uploaded by

lokbasnet368
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)
11 views20 pages

unit 2 text and number

Chapter 2 of the document covers working with text and numbers in PHP, including variables, data types, and built-in string functions. It explains the rules for PHP variables, the concept of loosely typed languages, and details various data types such as strings, integers, floats, and arrays. Additionally, it discusses operators in PHP, including arithmetic, assignment, and comparison operators.

Uploaded by

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

Contents

Chapter 2. Working with Text and Numbers ............................................................................................... 1


Variables in PHP ...................................................................................................................................... 1
Rules for PHP variables: .......................................................................................................................... 1
PHP is a Loosely Typed Language ............................................................................................................ 1
PHP Constants ......................................................................................................................................... 1
Syntax ................................................................................................................................................. 2
Example .............................................................................................................................................. 2
Example .............................................................................................................................................. 2
PHP Data Types ........................................................................................................................................... 2
PHP String ........................................................................................................................................... 3
Example .............................................................................................................................................. 3
PHP Integer ......................................................................................................................................... 3
Example .............................................................................................................................................. 3
PHP Float ............................................................................................................................................. 3
Example .............................................................................................................................................. 4
PHP Boolean ....................................................................................................................................... 4
PHP Array ............................................................................................................................................ 4
Example .............................................................................................................................................. 4
PHP Object .......................................................................................................................................... 4
Example .............................................................................................................................................. 4
PHP NULL Value .................................................................................................................................. 5
Example .............................................................................................................................................. 5
Strings ......................................................................................................................................................... 5
Built-in String Functions: ......................................................................................................................... 5
strlen() - Return the Length of a String ............................................................................................... 5
Example .............................................................................................................................................. 5
str_word_count() - Count Words in a String ....................................................................................... 6
Example .............................................................................................................................................. 6
strrev() - Reverse a String .................................................................................................................... 6
Example .............................................................................................................................................. 6
strpos() - Search For a Text Within a String ......................................................................................... 6
Example .............................................................................................................................................. 6
str_replace() - Replace Text Within a String ........................................................................................ 6
Example .............................................................................................................................................. 7
PHP strtolower() Function ................................................................................................................... 7
Example
<?php echo strtolower("Hello WORLD."); ?> ...................................................................................... 7
PHP strtoupper() Function .................................................................................................................. 7
Example .............................................................................................................................................. 7
PHP trim() Function ............................................................................................................................. 7
Syntax ..................................................................................................................................................... 7
Example .............................................................................................................................................. 8
PHP Numbers .......................................................................................................................................... 8
PHP Integers ........................................................................................................................................... 8
Example .............................................................................................................................................. 8
PHP Floats ............................................................................................................................................... 9
Example .............................................................................................................................................. 9
PHP Infinity ............................................................................................................................................. 9
Example .............................................................................................................................................. 9
PHP NaN................................................................................................................................................ 10
Example ............................................................................................................................................ 10
PHP Numerical Strings .......................................................................................................................... 10
Example ............................................................................................................................................ 10
PHP Casting Strings and Floats to Integers ............................................................................................ 11
Example ............................................................................................................................................ 11
PHP Operators .......................................................................................................................................... 11
PHP Arithmetic Operators..................................................................................................................... 11
PHP Assignment Operators ................................................................................................................... 12
PHP Comparison Operators .................................................................................................................. 13
PHP Increment / Decrement Operators ................................................................................................ 14
PHP Array Operators ............................................................................................................................. 15
PHP Conditional Assignment Operators ................................................................................................ 16
Chapter 2. Working with Text and Numbers

Variables in PHP

Variables are used for storing value, like strings, numbers or arrays. When a variable is declared,
it can be used over and over again in your script. All variable in PHP start with a $ sign symbol.

Syntax:

$var_name=value;

Let’s try creating a variable containing string and variable containing a number

<?php

$txt=”hello world”;

$x=32;

?>

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)

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.

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

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

Syntax
define(name, value, case-insensitive)

Parameters:

 name: Specifies the name of the constant


 value: Specifies the value of the constant
 case-insensitive: Specifies whether the constant name should be case-insensitive. Default
is false

Example

Create a constant with a case-sensitive name:

<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>

Example

Create a constant with a case-insensitive name:

<?php
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
?>

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

2
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
<?php
$x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";
echo $y;
?>

PHP Integer

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

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

In the following example $x is an integer. The PHP var_dump() function returns the data type
and value:

Example
<?php
$x = 5985;
var_dump($x);
?>

PHP Float

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

In the following example $x is a float. The PHP var_dump() function returns the data type and
value:

3
Example
<?php
$x = 10.365;
var_dump($x);
?>

PHP Boolean

A Boolean represents two possible states: TRUE or FALSE.

<?php $x = true;
$y = false;
?>

PHP Array

An array stores multiple values in one single variable.

In the following example $cars is an array. The PHP var_dump() function returns the data type
and value:

Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>

PHP Object

An object is a data type which stores data and information on how to process that data.

In PHP, an object must be explicitly declared.

First we must declare a class of object. For this, we use the class keyword. A class is a structure
that can contain properties and methods:

Example
<?php
class Car {
function Car() {
$this->model = "VW";
}
}

4
// create an object
$herbie = new Car();

// show object properties


echo $herbie->model;
?>

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.

Tip: 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:

Example
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>

Strings
Strings can be seen as stream of characters. For example , ‘G’ is a character and ‘BIM NOTES’
is string. A string is a sequence of characters, like "Hello world!".

Built-in String Functions:

Built-in function in PHP are some existing library function which can be used directly in our
programs making an appropriate call to them. Below are some important built-in string function
that we use in our daily and regular program.

strlen() - Return the Length of a String

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

Example

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

5
<?php
echo strlen("Hello world!"); // outputs 12
?>

str_word_count() - Count Words in a String

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!":

<?php
echo str_word_count("Hello world!"); // outputs 2
?>

strrev() - Reverse a String

The PHP strrev() function reverses a string.

Example

Reverse the string "Hello world!":

<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>

strpos() - Search For a 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.

Example

Search for the text "world" in the string "Hello world!":

<?php
echo strpos("Hello world!", "world"); // outputs 6
?>

str_replace() - Replace Text Within a String

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

6
Example

Replace the text "world" with "Dolly":

<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>

PHP strtolower() Function

The strtolower() function converts a string to lowercase.

Note: This function is binary-safe.

Related functions:

 strtoupper() - converts a string to uppercase


 lcfirst() - converts the first character of a string to lowercase
 ucfirst() - converts the first character of a string to uppercase
 ucwords() - converts the first character of each word in a string to uppercase

Example
<?php
echo strtolower("Hello WORLD.");
?>

PHP strtoupper() Function


The strtoupper() function converts a string to uppercase.

Example

Convert all characters to uppercase:

<?php
echo strtoupper("Hello WORLD!");
?>

PHP trim() Function


The trim() function removes whitespace and other predefined characters from both sides of a
string.

Syntax
trim(string,charlist)

7
Example

Remove characters from both sides of a string ("He" in "Hello" and "d!" in "World"):

<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>

PHP Numbers

One thing to notice about PHP is that it provides automatic data type conversion.

So, if you assign an integer value to a variable, the type of that variable will automatically be an
integer. Then, if you assign a string to the same variable, the type will change to a string.

PHP Integers

An integer is a number without any decimal part.

2, 256, -256, 10358, -179567 are all integers. While 7.56, 10.0, 150.67 are floats.

So, an integer data type is a non-decimal number between -2147483648 and 2147483647. A
value greater (or lower) than this, will be stored as float, because it exceeds the limit of an
integer.

PHP has the following functions to check if the type of a variable is integer:

 is_int()
 is_integer() - alias of is_int()
 is_long() - alias of is_int()

Example

Check if the type of a variable is integer:

<?php
$x = 5985;
var_dump(is_int($x));

$x = 59.85;
var_dump(is_int($x));
?>

8
PHP Floats

A float is a number with a decimal point or a number in exponential form.

2.0, 256.4, 10.358, 7.64E+5, 5.56E-5 are all floats.

The float data type can commonly store a value up to 1.7976931348623E+308 (platform
dependent), and have a maximum precision of 14 digits.

PHP has the following functions to check if the type of a variable is float:

 is_float()
 is_double() - alias of is_float()

Example

Check if the type of a variable is float:

<?php
$x = 10.365;
var_dump(is_float($x));
?>

PHP Infinity

A numeric value that is larger than PHP_FLOAT_MAX is considered infinite.

PHP has the following functions to check if a numeric value is finite or infinite:

 is_finite()
 is_infinite()

However, the PHP var_dump() function returns the data type and value:

Example

Check if a numeric value is finite or infinite:

<?php

$x = 1.9e411;

var_dump(is_infinite($x));
?>

9
PHP NaN

NaN stands for Not a Number.

NaN is used for impossible mathematical operations.

PHP has the following functions to check if a value is not a number:

 is_nan()

However, the PHP var_dump() function returns the data type and value:

Example

Invalid calculation will return a NaN value:

<?php
$x = acos(8);
var_dump(is_nan($x));
?>

PHP Numerical Strings

The PHP is_numeric() function can be used to find whether a variable is numeric. The function
returns true if the variable is a number or a numeric string, false otherwise.

Example

Check if the variable is numeric:

<?php
$x = 5985;
var_dump(is_numeric($x));

$x = "5985";
var_dump(is_numeric($x));

$x = "59.85" + 100;
var_dump(is_numeric($x));

$x = "Hello";
var_dump(is_numeric($x));
?>

10
PHP Casting Strings and Floats to Integers

Sometimes you need to cast a numerical value into another data type.

The (int), (integer), or intval() function are often used to convert a value to an integer.

Example

Cast float and string to integer:

<?php
// 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 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.

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

Assignment Same as... Description

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

12
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 === Returns true if $x is equal to $y, and they are of the
$y 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 is greater than or equal to $y

13
or equal to

<= Less than or $x <= $y Returns true if $x is less than or equal to $y


equal to

<=> Spaceship $x <=> Returns an integer less than, equal to, or greater than
$y 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 Name Description

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

$x++ Post-increment Returns $x, then increments $x by one

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

$x-- Post-decrement Returns $x, then decrements $x by one

PHP Logical Operators

The PHP logical operators are used to combine conditional statements.

Operator Name Example Result

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


assignment

PHP Array Operators

The PHP array operators are used to compare arrays.

15
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- $x !== $y Returns true if $x is not identical to $y


identity

PHP Conditional Assignment Operators

The PHP conditional assignment operators are used to set a value depending on conditions:

Operator Name Example Result

?: Ternary $x Returns the value of $x.


= expr1 ? expr2 : expr3 The value of $x is expr2 if expr1 =
TRUE.
The value of $x is expr3 if expr1 =
FALSE

?? Null $x = expr1 ?? expr2 Returns the value of $x.


coalescing The value of $x is expr1 if expr1 exists,
and is not NULL.
If expr1 does not exist, or is NULL, the

16
value of $x is expr2.
Introduced in PHP 7

17

You might also like