Unit 2:
Working with Text and Numbers
Compiled by: Er. Krishna KhadkaText
* When they are used in computer programs, pieces of text are called
strings.
* This is because they consist of individual items, combined together.
* Strings can contain letters, numbers, punctuation, spaces, tabs or any
other characters.
* Some examples of strings are “It is too hot, what is your name?”Defining Text Strings
* There are a few ways to indicate a string in PHP program. The
simplest is to surround the string with single quotes:
Print ‘It is too hot.
Print ‘chicken’;
Print ‘01234’;
* Output of above line is:
It is too hot.chicken01234
* “are delimiters, which tells the PHP engine where the start and end of
the string is.* You can also delimit strings with double quotes.
*The major difference between single quoted and double quoted
strings is that when you include variable names inside a double
quoted string, the value of the variable is substituted into the string,
which doesn’t happen with single quoted strings.
* For example:
Suser holds the value students, then ‘hello Suser’ is just that:
hello Suser.
However, “hello Suser” is hello students.example
"; hello students
3
echo"hello Suser";
?>exam ple To combine two strings, use a . (period),
the string concatenation operator. Here
Z ,
are some combined strings:
";
Print "It’s a beautiful day" . "in the neighborhood.";
echo" ";
Print "The price is:" . '230';
Print ‘hi’. 'hello' . 'bye';
> o/p
breadfruit
It’s a beautiful dayin the neighborhood.
The price is:230hihellobyeEscape sequence/character.
* If you want to include a single quote inside a string surrounded with single
quotes, put a backslash (\) before the single quote inside the string.
* The backslash tells the PHP engine to treat the following character as a
literal single quote instead of the single quote that means “end of string.”
* This is called escaping, and the backslash is called the escape character.
* An escape character tells the system to do something special with the
character that comes after it.
* Inside a single-quoted string, a single quote usually means “end of string.”
Preceding the single quote with a backslash changes its meaning to a literal
single quote character.
Defining strings with backslash o/p
<2php, : eo
We'll each have a bow! of soup.
‘Well each have a bowl of scup.Variables
* Variables hold the data that your program manipulates while it runs, such
as user information that you’ve loaded from a database or entries that
have been typed into an HTML form.
* In PHP, variables are denoted by a (dollar sign) $ followed by the variable’s
name.
* To assign a value to a variable, use an equals sign (=). This is known as the
assignment operator.
* Syntax of declaring a variable in PHP is given below:
Svariablename=value;
* Example
Variable names may only include:
* Uppercase or lowercase Basic Latin letters (A-Z and a-z)
* Digits (0-9)
* Underscore (_)
* Any non-Basic Latin character (such as ¢ ), if you’re using a character
encoding such as UTF-8 for your program file
* Additionally, the first character of a variable name is not allowed to
be a digit. Following Table lists some allowable variable names* Variable names are case-sensitive.
* This means that variables named $dinner, $Dinner, and $DINNER are
separate and distinctSor)
SdrinkSize
$SUPER_BIG_DRINK
a: a a
Rs Te CoP
STEVIA) 4* earlier were the list of some allowed variable names:NUE Rar Tut
iret
Tih Lara
$drinkmaster@example.com
RYT
PT ior aoe
iTS)
Begins with a number
Unacceptable character: -
Unacceptable characters: @ and.
Unacceptable character: !
Unacceptable character: +
Krichna Khadka+ Earlier were the list of some disallowed variable names and reasonManipulating Text
* PHP has a number of built-in functions that are useful when working
with strings.
* The most useful two common tasks: validation & formatting.
Validating Strings
* Validation is the process of checking that input coming from an
external source conforms to an expected format or meaning.
* It’s making sure that a user really entered a zip code in the “zip code”
box of a form or a reasonable email address in the appropriate place.* strlen()- which tells the length of a string,
* rtrim()- Removes whitespace or other predefined characters from the
right side of a string
* Itrim() - Removes whitespace or other predefined characters from the
left side of a string
trim() - Removes whitespace or other predefined characters from
both sides of a string
Syntax:
* trim(variable name or strings)
* Itrim(variable name or strings)
* rtrim(variable name or strings)
* strlen(variable name or strings)*To compare strings without paying attention to case, use
strcasecmp().
* It compares two strings while ignoring differences in capitalization.
*lf the two strings you provide to strcasecmp() are the same
independent of any differences between upper- and lowercase
letters, it returns 0.
* The strcmp() function is used to compare the strings without ignoring
the differences in capitalization.
* Syntax:
* strcasecmp(string1, string2)
* stremp(string1, string2)example:
$zipcode=trim($_POST[‘zipcode’]);
$zip_length=strlen(Szipcode);
If(Szip_length !=5) {
Print “please enter a zip code that is 5 character long.”;
}
//To compare two strings, use the equal operator (==),as shown below:
If (S_POST[‘email’]==’abc@pu.edu.np’)
{ The print statement will run only if the submitted
form parameter email is the all-lowercase
abe@pu.edu.np. When comparing string with ==,
i} case is important. The string abec@pu.edu.NP is not
the same as Abc@pu.edu.np or abe@pu.edu.np.
Print “welcome”;*To compare string without paying attention to case, use
strcasecmp(). It returns 0 if both strings are same.
if(strcasecmp($_POST[‘email’], ‘abc@pu.edu.np’)==0)
{
Print “welcome”;
}* The ucwords() function uppercases the first letter of each word in a
string.
* This is useful when combined with strtolower() to produce nicely capitalized
names when they are provided to you in all uppercase.
* The strtoupper() converts the string into uppercase.
* The substr() function, you can extract just part of a string.
* The three arguments to substr() are the string to work with, the starting
position of the substring to extract, and the number of bytes to extract.
* The beginning of the string is position 0, not 1.
* When you give substr() a negative number for a start position, it counts back
from the end of the string to figure out where to start.
* Astart position of -4 means “start four bytes from the end.”
* The str_replace() function changes parts of a string. It looks for a
substring and replaces the substring with a new stringSyntax:
* ucwords(string)
* strtolower(string)
* strtoupper(string)
* substr(string,start,length)
* str_replace(find,replace,string)Some examples
>
ofp
Hello World
ofp
hello world.
krishna Khadka 23
o/p
HELLO WORLD!
krishna Khadka
>
o/p
"5
echo substr("Hello world",1)." ";
echo substr(“Hello world”,3)." "3
echo substr(“Hello world",7)." ";
echo “ "5
// Negative numbers:
echo substr("Hello world”,-1)." "5
echo substr(“Hello world™,-10)
echo substr("Hello world",-8).
echo substr("Hello world" ,-4)."
>
krishna Khadkaofp
llo w
ello world
lo world
orld
d
ello world
lo world
orldFormatting text
* The printf() function give more control compared to print(), how the
output looks.
* Example
ofp
The dish costs $110,000
* The format string rules begin with % and then have some optional
modifiers that affect what the rule does:
* A padding character: If the string that is replacing the format rule is
too short, this is used to pad it.
* A sign: For numbers, a plus sign (+) makes printf() put a + before
positive numbers(normally, they are printed without a sign)
* Aminimum width: This specifies the minimum size that the value
replacing the format rule should be.
* Period & a precision number:
-For floating point number this controls how many digits go after the
decimal point.Zero-padding with printf()
$zip = '6520';
$month = 2;
$day = 6;
$year = 2007;
printf("ZIP is ¥05d and the date is 482d/%02d/%d", $zip, $month, $day, Syear);
It prints:
ZIP is 06520 and the date is 02/06/2007Displaying signs with printf()
o/p
the computer can operate between +40 and -40 degree celsius
‘More formatting:
* Strtolower()
* Strtoupper()
* Ucwords() function uppercase the first letter of each word in a string.
Print ucwords(strtolower(‘COLLEGE OF APPLIED BUSINESS’);2. strpos() function: This function takes two string arguments and if the second string is present in the first one, it will return
the starting position of the string otherwise returns FALSE. Example:The strpos() function is used to search for character
Example:-
1 <2php
|2 echo strpos("Hello world!", "world";
ES
output- 6
Krichna Khadka aaa)strrev() function: This function is used to reverse a string.
i
Output
Idirow olleH
krishna KhadkaNumbers
* Example
"; 3638
Print 56.33 0.777433
print " "; 0
Print 56.383 i
print " "; s
Print 0.777433;
print “ ";
Print 0;
print “ "5
Print -324;
print " ";
Print 0.00;
2>
Krishna Khadka
|Using different kinds of Numbers
-floating point number
-integer numberPHP 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
= Logical operators
krishna KhadkaArithmetic Operators
* + addition
* -Subtraction
+ / division
* *multiplication
* ** Exponentiation (for older version use, pow() function)
* % modulus divisionOperating on variable
";
Print ‘The total cost is *.$total_cost;
Print " "
Print $email_ Address;
>
Comparison Operators
Operand
<=
>=
Example
$variable1 == $variable2
$variable1 != $variable2
Svariable1 < Svariable2
Svariable1 > Svariable2
$variable1 <= $variable2
$variable1 >= $variable2
Meaning
Has the same value as
Is NOT the same value as
Less Than
Greater Than
Less than or equals to
Greater than or equals to
krishna Khadka: Assignment operators
x+=y x=xt+y
K-=y
x*=y x=x*y
x/=y x=x/y
x %=y x=x%y
peeeaa
nm
The left operand gets set to the value of the expression on
the right
Addition
Subtraction
Multiplication
Division
Modulus.Logical Operators
Operand Example
aa $variable1 && Svariable2
I $variable1 | | Svariable2
AND $variable1 AND Svariable2
XOR $variable1 XOR $variable2
OR $variable1 OR $variable2
! !$variable1
Meaning
Are both values true?
Is at least one value true?
Are both values true?
Is at least one value true, but NOT both?
Is at least one value true?
Is NOT something
krishna Khadka* End of unit 2